Writable Streams in Javascript


Writable streams have many powerful events and functions. Here are the most common events:

'error': This event will be emitted if an error happens during the writing or piping of data.

'finish': Emitted after the end() method has been called.

'close': Indicates that no more events will be emitted. It is emitted when the stream and any of its resources have been closed.

'pipe': Emitted when the pipe() method is called on a readable stream. It will basically feed the writable from the readable.

'unpipe': This event is the opposite of the 'pipe' event, and it will be emitted when the unpipe() method is called on a Readable stream. This will be also emitted when a Writable stream emits an error to the 'pipe'.

'drain': If the write() method returns false, the 'drain' event will be emitted when it again becomes ready to write. This can be caused because of different bandwidths and speeds of writing and reading.

Let's add events 'finish' and 'close' to an example:

const fs = require('fs'); const file = fs.createWriteStream('./big-file.txt'); for(let i = 0; i <= 1000000; i++) { file.write('...'); } file.on('close', () => { console.log('OnClose'); // 3 }); file.on('finish', () => { console.log('OnFinish'); // 1 }); file.end(() => { console.log('end'); // 2 });

If you run the code, you will see that the order of the outputs is the following:

  1. OnFinish
  2. end
  3. OnClose



Hot Deals ends in

Technical Quizzes Specially For You:


Search Tags