简体   繁体   English

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

[英]How do you read a file or Stream synchronously in node.js?

Please, no lectures about how I should be doing everything asynchronously. 请不要讲述我应该如何异步地做所有事情。 Sometimes I want to do things the easy obvious way, so I can move on to other work. 有时我想以简单明了的方式做事,所以我可以继续其他工作。

For some reason, the following code doesn't work. 由于某种原因,以下代码不起作用。 It matches code I found on a recent SO question . 它匹配我在最近的SO问题上找到的代码。 Did node change or break something? 节点改变或破坏了什么?

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

After the read, the buffer is null. 读取后,缓冲区为空。

Looking at rs in the debugger, I see 我看到调试器中的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

To read the contents of a file synchronously use fs.readFileSync 要同步读取文件的内容,请使用fs.readFileSync

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

fs.createReadStream creates a ReadStream . fs.createReadStream创建一个ReadStream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM