3

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);
NewbieCoder
  • 105
  • 9

1 Answers1

3

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.

nijm
  • 2,158
  • 12
  • 28
  • Oh ok, I'll try `fs.watch` and the others. Thank you. But still, shouldn't it atleast display what was already inside the file? – NewbieCoder Aug 17 '18 at 13:07
  • The default options of `fs.createWriteStream` will overwrite the file, so `./testfile.txt` will be empty when the read stream is created. If you want to append to the file you can use `fs.createWriteStream('./testfile.txt', { flags: 'a' })`. – nijm Aug 18 '18 at 15:16