代码:
#!/usr/bin/env node
// npm install sync-prompt
var prompt = require('sync-prompt').prompt;
var name = prompt('what is your name? ');
console.log('Hello ' + name);
var fruit = prompt('what is your favorite fruit? ');
console.log('me too');
process.on('SIGINT', function(){
process.exit(0);
});
console.log('this would be print after you type CTRL+C');
process.exit(0);
输出结果:
[honwhy@localhost nodejs]$ ./example.js
what is your name? honey
Hello honey
what is your favorite fruit? ^Cme too
this would be print after you type CTRL+C
由于process.on是异步执行的,所以在程序退出前还会输出me too
和this would be...
等语句。
有没有办法在程序(process)捕获到SIGINT
后同步方式执行,直接退出程序呢?
UPDATE
对原作者的模块源码做了一点修改了,提交了pull request
,不过貌似提交失败了,等待结果中。issue地址:https://github.com/shovon/sync-prompt/pull/9
(2014年7月7日 18:39:17)
It is indeed impossible to achieve with
process.on()
.I think this is
sync-prompt
's own problem. There are two problems here:cin.eof()
afterstd::getline()
. If checked, there would be a chance to notify the caller of this situation in some way. , giving the caller a chance to process it. In fact, not only Ctrl + C, if you press Ctrl + D to close stdin directly, you will have the same problem, and Ctrl + D is simply impossible to capture through signals.sync-prompt
It should not usecin
directly at all, which is wrong in itself. You can try it. If you writeprocess.stdin.on("end", function() {})
first and then executeprompt()
, you will find thatprompt()
will return immediately. At this time, if thecin.eof()
status is output in its source code, you can see that this returnstrue
. This is because thison()
call enables stream mode and closes the original stdin fd, causing the sentencegetline(cin, retval)
to not work at all.If you still want to continue using it, then implement the callback mechanism mentioned in the first item above, otherwise there will be no solution at all.
Update: I just took a look at the
sync-prompt
warehouse and found that the author added aprompt.isEOF()
function a few days ago, so I can finally make a judgment. Did you quit because of EOF? However, it seems that the latest code has not yet been released to the npm registry. If you want to use it, you need to manually download the code and compile it.