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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19918326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:15:46  来源:igfitidea点击:

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

javascriptnode.js

提问by user949300

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. Did node change or break something?

出于某种原因,以下代码不起作用。它匹配我在最近的一个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());

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

回答by Bulkan

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.createReadStreamcreates a ReadStream.

fs.createReadStream创建一个ReadStream