Writable Streams In Node.Js
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 :
-
write.
-
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.
[js]
http.createServer(req,res){
res.write(“Sahil ”);
res.end(“Chitkara”)
}
[/js]
Events:
-
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.
-
Finish: This event is emitted when end() is called.
Example
[js]
http.createServer(req,res){
res.write(“Sahil ”);
res.end(“Chitkara”);
res.on(‘finish’’,function(){
console.log(“writing data is now complete”);
});
}
[/js]
-
Pipe: This event is emitted when pipe() is called on readable stream and adding writable stream to its destination.
[js]
var fs= require(‘fs’)
var readable = fs.createReadStream(‘abc.txt’);
var writable=fs.createWriteStream(‘bcd.txt’);
readable.pipe(writable);
[/js]
-
Unpipe: This event is emitted when unpipe() is called on readable stream and adding writable stream to its destination.
[js]
var fs= require(‘fs’)
var readable = fs.createReadStream(‘abc.txt’);
var writable=fs.createWriteStream(‘bcd.txt’);
readable.unpipe(writable);
[/js]
-
Error: Emitted when error occurs while writing and piping the data.
[js]
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);
});
[/js]
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