https://github.com/nodejs/node/issues/7439
上面的页面显示fs.readFileSync(process.stdin.fd)
不能正确工作。
fs.readFileSync(fs.openSync('/dev/stdin', 'rs'))
是从stdin读取的正确方式吗?但它似乎只在某些情况下有效,而不是所有情况。我想知道在nodejs中从stdin读取的正确方式是什么。
https://github.com/nodejs/node/issues/7439
上面的页面显示fs.readFileSync(process.stdin.fd)
不能正确工作。
fs.readFileSync(fs.openSync('/dev/stdin', 'rs'))
是从stdin读取的正确方式吗?但它似乎只在某些情况下有效,而不是所有情况。您可以使用readline
https://nodejs.org/api/readline.html
从这些文档中:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
并且要读取行:
for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
}
process
全局对象有一个 stdin
接口。当用户输入文本并按下键盘上的 Enter
键后,它将记录一行日志。
let buffer = ''
process.stdin.resume()
process.stdin.on('data', (d) => buffer = buffer.concat(d.toString()))
setTimeout(() => {
// Exit after 5 seconds and print entered content
console.log(buffer.toString('utf8'))
process.exit(0)
}, 5000)
文档 - https://nodejs.org/api/process.html#process_process_stdin