Writable Streams In Node.Js

30 / Jan / 2014 by Sahil Chitkara 0 comments

In my previous blog we discussed about “Readable Streams in Node.js”. Here we will be learning about the next part of stream which is, writable stream.

Writable stream is used to write data to a specific destination.

Basically its has two main method :

  1. write.

  2. end

Write:
writable.write(chunk,[encoding],[callback])

This method is used to write the chunk of data to stream and call its corresponding callback after writing the data, if it is provided. Encoding is supplied if the chunk is a String.This method will return true if data is handled or ready to write more data.

End:

writable.end(chunk,[encoding],[callback])

This method is used to write last chunk of data on the stream and call its corresponding callback when it is finished writing. Finish event is attached with this callback. Encoding is supplied if the chunk is a String.

Lets take an example:

In this example I will be writing my first name using write() and the calling end() with my last name.

http.createServer(req,res){
res.write(“Sahil ”);
res.end(“Chitkara”)
}

Events:

  1. Drain: If writing data with writable.write(chunk) returns false, the drain event will indicate whether its is appropriate to write more data to stream.

  2. Finish: This event is emitted when end() is called.

Example

http.createServer(req,res){
res.write(“Sahil ”);
res.end(“Chitkara”);
res.on(‘finish’’,function(){
console.log(“writing data is now complete”);
});
}
  1. Pipe: This event is emitted when pipe() is called on readable stream and adding writable stream to its destination.

var fs= require(‘fs’)
var readable = fs.createReadStream(‘abc.txt’);
var writable=fs.createWriteStream(‘bcd.txt’);
readable.pipe(writable);
  1. Unpipe: This event is emitted when unpipe() is called on readable stream and adding writable stream to its destination.

var fs= require(‘fs’)
var readable = fs.createReadStream(‘abc.txt’);
var writable=fs.createWriteStream(‘bcd.txt’);
readable.unpipe(writable);
  1. Error: Emitted when error occurs while writing and piping the data.

var fs= require(‘fs’)
var readable = fs.createReadStream(‘abc.txt’);
var writable=fs.createWriteStream(‘bcd.txt’);
readable.pipe(writable);
writable.on(‘error’,function(err){
console.log(“error: ”+err);
});

General use case of writable streams in nodejs:

  • http request
  • http response
  • fs write streams
  • tcp sockets
  • child process

So, this was a brief  intro of  writable streams. Hope you’ve learned some good stuff here.

Thanks

FOUND THIS USEFUL? SHARE IT

Leave a comment -