所以我需要在终端中使用输入文件,当我编写以下 cat input.txt |节点 prog.js >result.txt
我的代码是:
var fs = require('fs');
var str = fs.readFileSync('input.txt', 'utf8');
str.replace(/^\s*[\r\n]/gm,"").split(/\s+/).forEach(function (s) {
return console.log(
s === 'bob'
? 'boy'
: s === 'alicia'
? 'girl'
: s === 'cookie'
? 'dog'
: 'unknown');
});
我需要我的代码来获取输入文档,无论用户给出的名称如何。获取用户输入的正确方法是什么?
最佳答案
如果你将一个值输出到node.js脚本,你必须监听readable
或data
process
可用的事件监听器目的。使用data
每当您使用 readable
时,事件监听器都会将流直接置于流动模式。事件监听器,您必须使用 process.stdin.read()
强制 stdin 进入流动模式。要写入另一个命令或另一个脚本,您必须使用 process.stdout.write()
,它是一个可写流。
流动模式
#!/usr/bin/env node
let chunks = "";
process.stdin.on("data", data => {
// data is an instance of the Buffer object, we have to convert it to a string
chunks += data.toString();
})
// the end event listener is triggered whenever there is no more data to read
process.stdin.on("end", () => {
// pipe out the data to another command or write to a file
process.stdout.write(chunks);
});
非流动模式
#!/usr/bin/env node
process.stdin.on("readable", () => {
const flowingMode = process.stdin.read();
// flowingMode will become null, whenever there is no more data to read
if ( flowingMode )
chunks += flowingMode.toString();
})
process.stdin.on("end", () => {
process.stdout.write(chunks);
})
为了防止自己承受所有这些压力,如果 readable
上有非逻辑,您可以执行以下操作:或data
事件处理程序
#!/usr/bin/env node
process.stdin.pipe(process.stdout);
如果你想在 end
时做某事事件监听器被触发你应该这样做
#!/usr/bin/env node
process.stdin.pipe(process.stdout, { end: false } );
process.stdin.on("end", () => /* logic */ );
当 end
事件监听器被触发执行您的代码
#!/usr/bin/env node
let chunk = "";
process.stdin.on("data", data => {
chunk += data.toString();
});
process.stdin.on("end", () => {
chunk.replace(/^\s*[\r\n]/gm,"").split(/\s+/).forEach(function (s) {
process.stdout.write(
s === 'bob'
? 'boy'
: s === 'alicia'
? 'girl'
: s === 'cookie'
? 'dog'
: 'unknown');
});
});
> cat input.txt | ./prog.js > result.txt
关于javascript - js 代码如何使用终端获取输入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52710067/