如何在nodejs中获得同步readline,或使用异步“模拟”它?

新手上路,请多包涵

我想知道是否有一种简单的方法来获得“同步”读取线或至少在 node.js 中获得同步 I/O 的外观

我使用这样的东西,但它很尴尬

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

var i = 0;
var s1 = '';
var s2 = '';

rl.on('line', function(line){
    if(i==0) { s1 = line; }
    else if(i==1) { s2 = line; }
    i++;
})

rl.on('close', function() {
    //do something with lines
})'

而不是这个,我宁愿它像这样简单

var s1 = getline(); // or "await getline()?"
var s2 = getline(); // or "await getline()?"

有用的条件:

(a) 不喜欢使用外部模块或 /dev/stdio 文件句柄,我正在向代码提交网站提交代码,但这些在那里不起作用

(b) 可以使用 async/await 或 generators

© 应该基于行

(d) 在处理之前不需要将整个标准输入读入内存

原文由 Colin D 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

以防万一将来有人偶然发现这里

节点 11.7 使用 async await 添加 了对此的支持

const readline = require('readline');
//const fileStream = fs.createReadStream('input.txt');

const rl = readline.createInterface({
  input: process.stdin, //or fileStream
  output: process.stdout
});

for await (const line of rl) {
  console.log(line)
}

记得把它包装在 async function(){} 否则你会得到一个 _reserved_keyworderror

 const start = async () =>{
    for await (const line of rl) {
        console.log(line)
    }
}
start()

要读取单个行,您可以手动使用 async 迭代器

const it = rl[Symbol.asyncIterator]();
const line1 = await it.next();

原文由 Aishwat Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

你可以把它包装在一个承诺中——

 const answer = await new Promise(resolve => {
  rl.question("What is your name? ", resolve)
})
console.log(answer)

原文由 Brian Burns 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题