36

拜托,没有关于我应该如何异步做所有事情的讲座。有时我想以简单明了的方式做事,这样我就可以继续其他工作了。

出于某种原因,以下代码不起作用。它与我在最近的 SO question中找到的代码相匹配。节点是否改变或破坏了什么?

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());

读取后,缓冲区为空。

在调试器中查看 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
4

1 回答 1

10

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

var fs = require('fs');
var content = fs.readFileSync('myfilename');
console.log(content);

fs.createReadStream创建一个ReadStream

于 2013-11-12T00:05:28.660 回答