你如何在node.js中同步读取文件或流?

use*_*300 32 javascript node.js

请不要讲述我应该如何异步地做所有事情.有时我想以简单明了的方式做事,所以我可以继续其他工作.

由于某种原因,以下代码不起作用.它匹配我在最近的SO问题上找到的代码.节点改变或破坏了什么?

var fs = require('fs');
var rs = fs.createReadStream('myfilename');  // for example
                                             // but I might also want to read from
                                             // stdio, an HTTP request, etc...
var buffer = rs.read();     // simple for SCCCE example, normally you'd repeat in a loop...
console.log(buffer.toString());
Run Code Online (Sandbox Code Playgroud)

读取后,缓冲区为空.

我看到调试器中的rs

events  
   has end and open functions, nothing else
_readableState
  buffer = Array[0]
  emittedReadable = false
  flowing = false   <<< this appears to be correct
  lots of other false/nulls/undefined
fd = null   <<< suspicious???
readable = true
  lots of other false/nulls/undefined
Run Code Online (Sandbox Code Playgroud)

Bul*_*kan 10

要同步读取文件的内容,请使用fs.readFileSync

var fs = require('fs');
var content = fs.readFileSync('myfilename');
console.log(content);
Run Code Online (Sandbox Code Playgroud)

fs.createReadStream创建一个ReadStream.

  • 是的,但是,我也希望能够从Streams中读取,而不仅仅是文件.我的坏,编辑问题澄清. (14认同)
  • @Shubham。不。我重新编写了异步代码,但看起来读取流同步(例如在启动时)仍然很有用 (2认同)