简体   繁体   中英

Can't read data from a stream in Node

Hi I am trying to read a file and convert into data by using the .createReadStream method, however, when I execute my program it gives me no errors, but it console.log's into the terminal 'undefined' Any advice will help thanks!

//Readable Steams
var fs = require("fs");
var data = '';

//Create a reable stream
var readerStream = fs.createReadStream('input.txt');

readerStream.setEncoding('utf8');

//Handle events data, end, error
readerStream.on('data', function(chunk){
  data += chunk;
});

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

readerStream.on('error', function(err){
  console.log(err.stack);
});

console.log("program ended");

Here:

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

You are appending to your global variable "data" you defined on line 3. However when you are in your callback for the "end" state, you expect it to give you a variable called "data" also, which you then log. Change the callback for end to this:

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

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