Fostah
Fostah

Reputation: 2946

Nodejs Fstream Multiple 'end' callbacks fired when piping multiple files

Issue: I am trying to figure out a way to only fire one 'end' event when piping multiple files to fstream.Reader.

Platform: Node 0.6.21

Is there a better way to handle this?

  var r = fstream.Reader({

    path: source, // source is a directory with two files.

    type: 'File'

  }).pipe(zlib.createGunzip()).pipe(tar.Extract({

    strip: strip,

    path: destination

  }));

  r.on('end', function() {
     // this is firing everytime a file is extracted. Ideally, I would only fire one 'end' event.
    if (typeof callback === 'function') {

      return callback(null);

    }

  });

Result when extracting two files = two 'end' callbacks. Any advice is appreciated. Thanks.

Upvotes: 1

Views: 1138

Answers (2)

Fostah
Fostah

Reputation: 2946

Turned out this was a known issue for node 0.6. If you are having this issue you will want to avoid using streams or upgrade your node.

Upvotes: 0

bendecoste
bendecoste

Reputation: 798

Can you use other libraries? Lodash#after or Underscore#after would help here.

You could do something like

// call `next` twice will call then call `callback`
var next = _.after(2, callback);

var r = fstream.Reader({
  path: source, // source is a directory with two files.
  type: 'File'
}).pipe(zlib.createGunzip()).pipe(tar.Extract({
  strip: strip,
  path: destination
}));

r.on('end', function() {
  next();
});

Or, using async

function read(p, next) {
  var r = fstream.Reader({path: p}); // read code like above
  r.on('end', next);
}

var tasks = [
  read.bind(null, 'path/to/first/file'),
  read.bind(null, 'path/to/second/file')
];

// callback will be called after all files do `end` .. only once
async.parallel(tasks, callback);

Upvotes: 1

Related Questions