0

I tried with versions, 10/14/16 and I'm using a mac.

My code base is quite complex, so I tried out something simple as below, yet nothing changed.

Is there something, I'm missing out?

`

const fs = require('fs');
const readableStream = fs.createReadStream('file.txt', 'utf8');
const writableStream = fs.createWriteStream('file-2.txt');

readableStream.on('open', function () {
  console.log('opening file')
  readableStream.on('data', (chunk) => {
    console.log(chunk)
      writableStream.write('hey there','utf8', () => {
        console.log('Im done writing!')
      });
  });
  writableStream.end();
})

` By the way, as expected I get no errors and the process exit quietly.

I tried the simple snippet above, expecting the file-2.txt to be created and the text "hey there" to be write on it.

Indeed the file is created but, it's empty.

Like I said before, I tried changing node versions(10/14/16) but same results.

I don't know what seems to cause this unexpected result. Any help will be appreciated.

1 Answers1

0

I think i figured out what the issue was. I must admit that, it's quite ridiculous :)

The problem was with the following line getting executed way before the write(filePath) has the time to finish creating and adding the chunk to the newly created file.

There are 2 ways to solve this problem, at last as far as I can tell.

1- Remove the line:

writeStream.end()

2- Added a callback that is called after writing is completed and call end in the callback like so:

writeStream('sometext', () => { done writing.... writeStream.end() })

3- Add a 'finish' event listener to the writeStream and to it's callback function, call the end() like so

writeStream('finish', () => { writeStream.end() })

Hope that helps some novice like myself out there!