在node.js
中有一种简单的方法可以做这样的事情,即一个函数,例如readline
从stdin
读取一行并返回一个字符串吗?
let a = parseInt(readline(stdin));
let b = parseFloat(readline(stdin));
我不希望阅读整行代码并逐行解析,例如使用process.stdin.on("data")
或rl.on("line")
。
在http://stackoverflow.com/questions/20086849/how-to-read-from-stdin-line-by-line-in-node中提供的答案中,每一行都由同一个功能块处理,我仍然无法在读取一行时将每一行分配给一个变量。
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', function(line){
console.log(line);
})
答案 0 :(得分:2)
很明显,从流中读取一条线无论如何都将是一个异步操作。 (因为你不知道线路实际出现在流中的时间)。所以你应该处理回调/承诺或发电机。当读取发生时,你得到一行(在一个回调中,作为一个返回的值.then或者只是通过将它分配给一个变量,如果你使用生成器)。
因此,如果它是您使用ES6的选项,并且可以选择' co'在这里运行生成器是你可以尝试的。
const co = require('co');
//allows to wait until EventEmitter such as a steam emits a particular event
const eventToPromise = require('event-to-promise');
//allows to actually read line by line
const byline = require('byline');
const Promise = require('bluebird');
class LineReader {
constructor (readableStream) {
let self = this;
//wrap to receive lines on .read()
this.lineStream = byline(readableStream);
this.lineStream.on('end', () => {
self.isEnded = true;
});
}
* getLine () {
let self = this;
if (self.isEnded) {
return;
}
//If we recieve null we have to wait until next 'readable' event
let line = self.lineStream.read();
if (line) {
return line;
}
yield eventToPromise(this.lineStream, 'readable');
//'readable' fired - proceed reading
return self.lineStream.read();
}
}

我用它来运行它以进行测试。
co(function *() {
let reader = new LineReader(process.stdin);
for (let i = 0; i < 100; i++) {
//You might need to call .toString as it's a buffer.
let line = yield reader.getLine();
if (!line) {break;}
console.log(`Received the line from stdin: ${line}`);
}
});
&#13;
如果您正在使用koa.js(基于生成器的类似Express的框架),它肯定会开箱即用
如果你不想要ES6,你可以在裸露的Promise上做同样的事情。它会是这样的。 http://jsbin.com/qodedosige/1/edit?js