Search code examples
javascriptnode.jsnode.js-stream

Writing and reading to a file using streams


The below code writes to a file whatever I type in the console. It also simultaneously reads from the same file and displays whatever that's in the file.

Everything I type in the console is saved in the file. I manually went and checked it. But whatever I type doesn't get displayed simultaneously.

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);

Why isn't this the same as the following?

process.stdin.pipe(process.stdout);

Solution

  • The read stream will be closed when the data in ./testfile.txt is fully piped. It will not wait for additional entries or changes.

    You can use fs.watch, to listen for file changes or even better use something easier like tail-stream or node-tail.