Pablo Pablo - 1 year ago 133
Node.js Question

Proper way to pipe buffers in Node JS

Take a look:

var Client = require('ftp');
var fs = require('fs');

var c = new Client();
c.on('ready', function() {
c.get('foo.txt', function(err, stream) {
if (err) throw err;
stream.once('close', function() { c.end(); });
// connect to localhost:21 as anonymous

This piece of code is from Basically it opens a read stream and pipes it into a write stream. At the end It closes the connection from the source.

Does the pipe method close the target stream after the piped stream (source) is closed? I couldn't find it on the API Documentation.

I made some test that from witch I can conclude it does it but I am no sure.

Answer Source

The destination stream is closed when the source emits an end event. This is documented in Stream.pipe:

By default end() is called on the destination when the source stream emits end, so that destination is no longer writable.

This allows calls of the form:

var http = require('http'),
  fs = require('fs');

http.createServer(function (req, res) {

If end wasn't called on the response object, the request would time out.

This would make the request time out:

  fs.createReadStream('path/to/file').pipe(res, {end: false});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download