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

请不要讲我应该如何asynchronous做所有事情。 有时候我想用简单明了的方式做事情,所以我可以继续做其他工作。

出于某种原因,下面的代码不起作用。 它匹配我在最近的SO问题上find的代码。 节点是否改变或破坏了某些东西

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

读取之后,缓冲区为空。

在debugging器看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创build一个ReadStream 。