如何在节点中逐行从stdin读取 [英] How to read from stdin line by line in Node

查看:75
本文介绍了如何在节点中逐行从stdin读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下命令行调用来处理带有node的文本文件:

I'm looking to process a text file with node using a command line call like:

node app.js < input.txt

文件的每一行都需要单独处理,但是一旦处理完,输入行可能会被忘记.

Each line of the file needs to be processed individually, but once processed the input line can be forgotten.

使用stdin的数据监听器,我将输入流按字节大小分块,因此进行了设置.

Using the on-data listener of the stdin, I get the input steam chunked by a byte size so I set this up.

process.stdin.resume();
process.stdin.setEncoding('utf8');

var lingeringLine = "";

process.stdin.on('data', function(chunk) {
    lines = chunk.split("\n");

    lines[0] = lingeringLine + lines[0];
    lingeringLine = lines.pop();

    lines.forEach(processLine);
});

process.stdin.on('end', function() {
    processLine(lingeringLine);
});

但是这看起来太草率了.必须在line数组的第一项和最后一项周围进行按摩.有没有更优雅的方式做到这一点?

But this seems so sloppy. Having to massage around the first and last items of the lines array. Is there not a more elegant way to do this?

推荐答案

您可以使用 readline 模块进行读取逐行输入stdin:

You can use the readline module to read from stdin line by line:

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

rl.on('line', function(line){
    console.log(line);
})

这篇关于如何在节点中逐行从stdin读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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