我理解 Node.js 中异步事件的基本原理,并正在学习如何以这种方式编写代码。然而,我陷入了以下情况:
我想编写代码,偶尔暂停用户输入。
该程序并不打算作为服务器(尽管目前它是用于命令行)。我知道这是 Node 的非典型用法。我的目标是最终将程序迁移回客户端 Javascript 应用程序,但是我发现在 Node.js 中工作对于调试来说既有趣又非常有用。这让我想起了我的例子,它说明了这个问题:
It reads in a text file and outputs each line unless the line ends with a "?". In that case, it should pause for user to clarify what was meant by that line. Currently my program outputs all lines first and waits for the clarifications at the end.
有没有什么方法可以强制 node.js 在命令行输入时暂停,以便在条件触发的情况下(即,该行以“ ?”结束)精确地输入命令行?
var fs = require("fs");
var filename = "";
var i = 0;
var lines = [];
// modeled on http://st-on-it.blogspot.com/2011/05/how-to-read-user-input-with-nodejs.html
var query = function(text, callback) {
process.stdin.resume();
process.stdout.write("Please clarify what was meant by: " + text);
process.stdin.once("data", function(data) {
callback(data.toString().trim());
});
};
if (process.argv.length > 2) {
filename = process.argv[2];
fs.readFile(filename, "ascii", function(err, data) {
if (err) {
console.error("" + err);
process.exit(1);
}
lines = data.split("\n");
for (i = 0; i < lines.length; i++) {
if (/\?$/.test(lines[i])) { // ask user for clarification
query(lines[i], function(response) {
console.log(response);
process.stdin.pause();
});
}
else {
console.log(lines[i]);
}
}
});
}
else {
console.error("File name must be supplied on command line.");
process.exit(1);
}