Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js ReadStream never calls 'data' listener

I have a file called a.txt which I can open and read using fs.readFile. However, I can't seem to read it with createReadStream:

var fs = require('fs');

var stream = fs.createReadStream('a.txt');
stream.on('data', function() { console.log('data present'); });

This never prints anything, what am I missing?

like image 770
Diego Avatar asked Sep 02 '25 13:09

Diego


1 Answers

Had this exact situation happen to me. What's happening when you run this code in the REPL is that the control flow is going back to node's event loop in between each line you type. When that happens node is taking the opportunity to do any pending IO. But because you haven't attached a listener, the 'data' events sail merrily off into oblivion.

You can verify this by pasting the code above into a javascript file and running it as a script. It works fine then because the listener gets attached before control returns to the event loop.

The version of this problem we encountered was when opening a stream and trying to work with it in a callback. Opening the stream in the enclosing function and referring to it from the callback didn't work - node had already pumped all the data out before our event listener was attached.

You can solve this one of two ways: either call pause on the stream as soon as you open it or be sure to attach your listeners before going through any callbacks.

like image 175
Darren Avatar answered Sep 05 '25 03:09

Darren