简体   繁体   English

无法从Node中的流读取数据

[英]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! 嗨,我正在尝试使用.createReadStream方法读取文件并将其转换为数据,但是,当我执行程序时,它没有给我任何错误,但是console.log位于终端“未定义”位置。任何建议都将对您有所帮助!

//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. 您将追加到在第3行中定义的全局变量“ data”。但是,当您处于“ end”状态的回调中时,您希望它也为您提供一个名为“ data”的变量,然后您将其记录下来。 Change the callback for end to this: 将回调更改为此:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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