a blog for those who code

Thursday, 17 December 2015

Writable Streams in Nodejs

In this post we will be discussing about writable streams in Nodejs. Streams are one of the most important components of Node.js. Node.js is an event-based platform where the most efficient way to handle I/O is - consuming the input as soon as it is available and sending the output as soon as it is produced. In our previous post we have discussed about Readable Streams in Nodejs.

Writable Stream

A writable stream will let you write data to a destination. Like readable streams, writable streams are also EventEmitters and emit various events at various points. Pushing some data to a writable stream is very easy, we just need to use the write() method as shown below :

writable.write(chunk, [encoding], [callback]) where encoding argument and callback argument are optional. To specify that no more data will be written to the stream you have to use end() method writable.end([chunk], [encoding], [callback]).

var fs = require('fs');
var streamRead = fs.createReadStream('test1.txt');
var streamWrite = fs.createWriteStream('test2.txt');

streamRead.setEncoding('utf8');

streamRead.on('data', function(chunk) {
  streamWrite.write(chunk);
});

In the above code we reads the data from an input stream (test1.txt) and writes to the destination (test2.txt) using write(). The write() function returns true when the write was successful and false when something went wrong.

When you do not have more data to write you can simply call end() method to notify the stream that you have finished writing. When end() is called , a finished event is emitted by the stream. You cannot write to stream after calling end(). So the above code will change to

var fs = require('fs');
var streamRead = fs.createReadStream('test1.txt');
var streamWrite = fs.createWriteStream('test2.txt');

streamRead.setEncoding('utf8');

streamRead.on('data', function(chunk) {
  streamWrite.write(chunk);
});

streamWrite.end(); // to signal end of data

Events related to writable streams are :

1. error - emitted to indicate that an error has occurred while writing.
2. pipe - emitted when readable stream is piped into a writable stream.
3. unpipe - emitted when you call unpipe on the readable stream to stop it from piping into the destination stream.

Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License