Bar*_*rio 19 javascript keypress node.js
我需要一个函数来暂停脚本的执行,直到按下一个键.我试过了:
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();
});
Run Code Online (Sandbox Code Playgroud)
但它只是在听按键而没有任何反应.该程序不会继续执行.
我该如何暂停执行?
vku*_*kin 20
适合我:
console.log('Press any key to exit');
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on('data', process.exit.bind(process, 0));
Run Code Online (Sandbox Code Playgroud)
mol*_*son 15
在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)
Run Code Online (Sandbox Code Playgroud)
或者如果你想让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()
}))
}
Run Code Online (Sandbox Code Playgroud)
接受的解决方案是异步等待按键事件然后退出,并不是真正的“按任意键继续”的解决方案。
我在编写一些 nodejs shell 脚本时需要暂停。我最终将 child_process 的 spawnSync 与 shell 命令“read”一起使用。
这将基本上暂停脚本,当您按 Enter 时,它将继续。很像 windows 中的 pause 命令。
require('child_process').spawnSync("read _ ", {shell: true, stdio: [0, 1, 2]});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
如果您不想退出该流程,则此代码段可以完成此工作:
console.log('Press any key to continue.');
process.stdin.once('data', function () {
continueDoingStuff();
});
Run Code Online (Sandbox Code Playgroud)
它是异步的,因此无法按原样在循环内工作-如果您使用的是Node 7,则可以将其包装在promise中并使用async/await
。
有一个包可以做到这一点: 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')
})
Run Code Online (Sandbox Code Playgroud)
在W10中运行没有问题。