请没有关于我应该如何异步执行所有操作的讲座。有时我想以显而易见的方式做事,所以我可以继续其他工作。
由于某些原因,以下代码不起作用。它与我在recent 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
最佳答案
要同步读取文件的内容,请使用fs.readFileSync
var fs = require('fs');
var content = fs.readFileSync('myfilename');
console.log(content);
fs.createReadStream创建一个ReadStream。
关于javascript - 如何在node.js中同步读取文件或流?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19918326/