【问题标题】:Node.js read stream not reading properly from fileNode.js 读取流未从文件中正确读取
【发布时间】:2016-02-24 11:52:12
【问题描述】:

我有一个文件,其中一行包含我需要使用的 id。在这种情况下,id 在文件的第一行,就是这个 9e598f1c-62d4-4b39-ac2d-ca8c5611c6b7

但是当我尝试使用带有此代码的读取流从文件中读取时

  var file_stream = fs.createReadStream(file_path);

  file_stream.on('readable', () => {
  console.log('readable:', file_stream.read());
  });

  file_stream.on('end', () => {
  console.log('end');
  });

我得到这个输出

readable: <Buffer 39 65 35 39 38 66 31 63 2d 36 32 64 34 2d 34 62 33 39 2d 61 63 32 64 2d 63 61 38 63 35 36 31 31 63 36 62 37>
readable: null
end

这绝对不是我在文件中的内容。会发生什么?

【问题讨论】:

  • bolav 给了你答案,但是对于一行数据,不要羞于使用fs.readFileSync():var content = fs.readFileSync(file_path).toString();
  • @ShanShan 我最终使用了这个选项,因为我需要稍后阅读几行,所以谢谢!这两个答案几乎都达到了他们的目的。

标签: node.js stream


【解决方案1】:

它是您文件的内容,只是以字节表示。试试这个把它找回来:

file_stream.on('readable', () => {
  var buf = file_stream.read()
  if (buf != null) {
    console.log('readable:', buf.toString());
  }
});

【讨论】:

    猜你喜欢
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多