如何在节点中逐行从stdin读取

编程入门 行业动态 更新时间:2024-10-27 18:25:28
本文介绍了如何在节点中逐行从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读取

本文发布于:2023-07-06 07:52:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047535.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   如何在   stdin   中逐行

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!