使用流写入和读取文件

Writing and reading to a file using streams

无论我在控制台中键入什么,下面的代码都会写入一个文件。它还同时从同一个文件中读取并显示文件中的任何内容。

我在控制台中输入的所有内容都保存在文件中。我手动去检查了它。但是无论我输入什么,都不会同时显示。

const fs = require('fs');
const Wstream = fs.createWriteStream('./testfile.txt', {encoding: 'utf8'});
const Rstream = fs.createReadStream('./testfile.txt', {encoding: 'utf8'});
process.stdin.pipe(Wstream);
Rstream.pipe(process.stdout);

为什么这和下面的不一样?

process.stdin.pipe(process.stdout);

read stream 将在 ./testfile.txt 中的数据完全通过管道传输后关闭。它不会等待其他条目或更改。

您可以使用 fs.watch, to listen for file changes or even better use something easier like tail-stream or node-tail.