我想用一些控制台扩展来制作一个简单的服务器 http 服务器。我找到了从命令行数据中读取的片段。
var i = rl.createInterface(process.stdin, process.stdout, null);
i.question('Write your name: ', function(answer) {
console.log('Nice to meet you> ' + answer);
i.close();
process.stdin.destroy();
});
重复提问,我不能简单地使用 while(done) { }
循环吗?同样,如果服务器在提问时收到输出,它会破坏线路。
最佳答案
你不能做一个“while(done)”循环,因为这需要阻塞输入,这是 node.js 不喜欢做的。
而是设置每次输入内容时调用的回调:
var stdin = process.openStdin();
stdin.addListener("data", function(d) {
// note: d is an object, and when converted to a string it will
// end with a linefeed. so we (rather crudely) account for that
// with toString() and then trim()
console.log("you entered: [" +
d.toString().trim() + "]");
});
关于node.js - 以交互方式从控制台读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8128578/