【问题标题】:Async stdin using readline使用 readline 的异步标准输入
【发布时间】:2023-02-26 05:33:21
【问题描述】:

我正在查看 O'Reilly 书中的一个示例“JavaScript:权威指南”,并试图进行一些更改。

当您使用输入重定向时,这个例子在书中写得很好:

node charfreq.js < input.txt

但我想进行更改,以便用户可以通过 Win cmd 行输入行,完成后 (ctrl+D),让脚本继续。为此,我尝试使用 readline 而不是 process.stdin,但无法让 asyn 工作。

这是原始代码:

async function histogramFromStdin() {
    process.stdin.setEncoding("utf-8"); // Read Unicode strings, not bytes
    let histogram = new Histogram();
    for await (let chunk of process.stdin) {
        histogram.add(chunk);
    }

    return histogram;
}

// This one final line of code is the main body of the program.
// It makes a Histogram object from standard input, then prints the histogram.
histogramFromStdin().then(histogram => { console.log(histogram.toString()); });

到目前为止,这是我尝试过的:

这里的问题是对 console.log(histogram.toString()); 的调用立即发生,而直方图仍未定义。不确定在哪里等待。

async function histogramFromStdin() {
    var readline = require('readline');
    process.stdin.setEncoding('utf-8');
    let histogram = new Histogram();

    var rl = readline.createInterface({ input: process.stdin, output: process.stdout });
    rl.setPrompt('> ');
    rl.prompt();
    rl.on('line', function (chunk) { histogram.add(chunk); rl.prompt(); });
    rl.on('close', function () { console.log('Input has closed'); return histogram; });
}

// This one final line of code is the main body of the program.
// It makes a Histogram object from standard input, then prints the histogram.
histogramFromStdin().then(histogram => { console.log(histogram.toString()); });

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您可以根据文档使用async/awaitevents 的混合方法:Example: Read file stream line-by-Line: a mixed approach

    尝试这个:

    const readline = require('readline');
    const {once} = require('events');
    
    async function histogramFromStdin() {
    
        process.stdin.setEncoding('utf-8');
        let histogram = new Histogram();
      
        try {
            
            const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
    
            rl.setPrompt('> ');
            rl.prompt();
            rl.on('line', function (chunk) { histogram.push(chunk); rl.prompt(); });
    
            await once(rl, 'close');
    
            console.log('Input has closed');
    
            return histogram;
    
        } catch (err) {
    
            console.error(err);
        }
    
    
    }
    
    // This one final line of code is the main body of the program.
    // It makes a Histogram object from standard input, then prints the histogram.
    histogramFromStdin().then(histogram => { console.log(histogram.toString()); })
    

    【讨论】:

      最近更新 更多