node.js:使用 readline 从文件中获取输入并在 Windows 命令提示符中处理

我想使用node.js从命令提示符运行 name.js 文件,并传递输入文件并在 output.txt 中重定向该输出,我正在为此编写一个命令,但这node name.js < input.txt | > output.txt不起作用或者我错了。


name.js 看起来像这样:


const readline = require('readline');


const rl = readline.createInterface({

  input: process.stdin,

  output: process.stdout

});

var _line = "";

rl.on('line', function(line){

    _line += line;

});

rl.on('pause', function(_line){

    console.log(_line);

});

我也尝试过这个Powershell -Command "command"


编辑:例如 input.txt 包含


hello js

hello node

hello world!

现在,如果我跑node name.js < input.txt > output.txt。我只是在output.txt中得到console.log()的“ undefined ”的返回值


守着星空守着你
浏览 68回答 1
1回答

泛舟湖上清波郎朗

将_line传递给 rl.on('pause',function( _line ){} 隐藏全局_line这就是为什么它给出 undefined 并且 cmd 命令没问题。还有其他方法可以通过使用Node.js 的进程 I/O来做到这一点function YourData(input) {} process.stdin.resume();process.stdin.setEncoding("ascii");_input = "";process.stdin.on("data", function (input) {    _input += input;});process.stdin.on("end", function () {   YourData(_input);});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript