简体   繁体   中英

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?

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.

Try:

var data = '';

var rs = fs.createReadStream('/path/to/file');

rs.on('data', function(data) {
  data += data;
});

rs.on('end', function() {
  console.log(data);
});

Just to be sure, try getting the path to the file correctly.

var path = __dirname + '/a.txt';
console.log(path);
var stream = fs.createReadStream(path);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM