如何获得同步读取线,或“模拟"它在 nodejs 中使用异步吗? [英] How to get synchronous readline, or "simulate" it using async, in nodejs?

查看:52
本文介绍了如何获得同步读取线,或“模拟"它在 nodejs 中使用异步吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wondering if there is a simple way to get "synchronous" readline or at least get the appearance of synchronous I/O in node.js

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

I use something like this but it is quite awkward

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 文件句柄,我正在向代码提交网站提交代码,但这些在那里不起作用

(a) Prefer not using external modules or /dev/stdio filehandle, I am submitting code to a code submission website and these do not work there

(b) 可以使用 async/await 或生成器

(b) Can use async/await or generators

(c) 应该是基于行的

(c) Should be line based

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

(d) Should not require reading entire stdin into memory before processing

推荐答案

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

Node11.7 添加了对此 doc_link 的支持,使用异步等待

Node11.7 added support for this doc_link using 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 函数中,否则你会得到reserver_keyword_error

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

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

To read an individual line you can use the async iterator manually

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

这篇关于如何获得同步读取线,或“模拟"它在 nodejs 中使用异步吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆