我需要一个函数来暂停脚本的执行,直到按下一个键。我试过了:
var stdin = process.openStdin();
require('tty').setRawMode(true);
stdin.on('keypress', function (chunk, key) {
process.stdout.write('Get Chunk: ' + chunk + '\n');
if (key && key.ctrl && key.name == 'c') process.exit();
});
但它只是在听按键而没有任何反应。该程序不会继续执行。
我该如何暂停执行?
适合我:
console.log('Press any key to exit');
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on('data', process.exit.bind(process, 0));
在node.js 7.6及更高版本中,您可以执行以下操作:
const keypress = async () => {
process.stdin.setRawMode(true)
return new Promise(resolve => process.stdin.once('data', () => {
process.stdin.setRawMode(false)
resolve()
}))
}
;(async () => {
console.log('program started, press any key to continue')
await keypress()
console.log('program still running, press any key to continue')
await keypress()
console.log('bye')
})().then(process.exit)
或者如果你想让CTRL-C退出程序而任何其他键继续正常执行,那么你可以用这个函数替换上面的“按键”功能:
const keypress = async () => {
process.stdin.setRawMode(true)
return new Promise(resolve => process.stdin.once('data', data => {
const byteArray = [...data]
if (byteArray.length > 0 && byteArray[0] === 3) {
console.log('^C')
process.exit(1)
}
process.stdin.setRawMode(false)
resolve()
}))
}
如果您不想退出进程,此代码段可以完成此任务:
console.log('Press any key to continue.');
process.stdin.once('data', function () {
continueDoingStuff();
});
它是异步的所以不会在循环内部工作 - 如果你使用的是Node 7,你可以将它包装在一个promise中并使用async/await
。
接受的解决方案异步等待一个关键事件然后退出,它实际上不是“按任意键继续”的解决方案。
我需要在编写一些nodejs shell脚本时暂停。我最终使用shell命令“read”使用了child_process的spawnSync。
这将基本上暂停脚本,当您按Enter键时它将继续。很像windows中的pause命令。
require('child_process').spawnSync("read _ ", {shell: true, stdio: [0, 1, 2]});
希望这可以帮助。
var fs = require("fs")
var fd = fs.openSync("/dev/stdin", "rs")
fs.readSync(fd, new Buffer(1), 0, 1)
fs.closeSync(fd)
这个答案取自node.js: readSync from stdin?的vadzim
有一个包:press-any-key
这是一个例子:
const pressAnyKey = require('press-any-key');
pressAnyKey("Press any key to resolve, or CTRL+C to reject", {
ctrlC: "reject"
})
.then(() => {
console.log('You pressed any key')
})
.catch(() => {
console.log('You pressed CTRL+C')
})
它在W10中运行没有问题。
const fs = require('fs');
process.stdin.setRawMode(true);
fs.readSync(0, Buffer.alloc(1), 0, 1);
60%的时间,它每次都有效。
我实际上制作了一个名为paktc
的npm包,可以帮助你解决这个问题。如果您安装包:
> npm install paktc
然后你会像这样使用它:
// your console application code here...
require('paktc') // Press any key to continue...