Cherry
Cherry

Reputation: 33534

Why it is needed to invoke close after finish in nodejs stream?

Here is a source:

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

var download = function(url, dest, cb) {
  var file = fs.createWriteStream(dest);
  var request = http.get(url, function(response) {
    response.pipe(file);
    file.on('finish', function() {
      file.close(cb);  // close() is async, call cb after close completes.
    });
  }).on('error', function(err) { // Handle errors
    fs.unlink(dest); // Delete the file async. (But we don't check the result)
    if (cb) cb(err.message);
  });
};

Why file.close(cb) is called on finish event? Does not finish close a stream? Look strange.

Upvotes: 0

Views: 483

Answers (1)

Rami Jarrar
Rami Jarrar

Reputation: 4643

Before NodeJS version 5.5.0 it was the application's responsibility to close the file descriptor and make sure there's no file descriptor leak.

In v5.5 they introduced the autoClose attribute for the method createWriteStream with a default value of true which means on error or finish the file descriptor will be closed automatically.

The source you're looking at was before v5.5.0 (2016-01-21)

Upvotes: 1

Related Questions