Skip to content

Instantly share code, notes, and snippets.

@chartjes
Created November 15, 2012 22:23
Show Gist options
  • Save chartjes/4081814 to your computer and use it in GitHub Desktop.
Save chartjes/4081814 to your computer and use it in GitHub Desktop.
var fs = require('fs');
var stream = fs.createReadStream('./test/fixtures/current');
var currentData = '';
stream.on('error', function (err) {
throw err;
});
stream.on('data', function (data) {
currentData += data;
});
// I want currentData to contain the contents of my file but
// console.log(currentData) shows nothing is in there.
// what am I missing?
console.log(currentData);
@kalifg
Copy link

kalifg commented Nov 16, 2012

You'll have to put the console.log inside of the event listener:

stream.on('data', function (data) {
    currentData += data;
    console.log(currentData);
});

The current call to console.log executes on a separate path, probably before a data event is generated.

If you are just try to collect all the output of that file/pipe, you could use one of the blocking fs functions, such as fs.readFileSync

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment