【问题标题】:How do you read a file or Stream synchronously in node.js?如何在 node.js 中同步读取文件或 Stream?
【发布时间】:2013-11-23 23:04:30
【问题描述】:

请不要讲我应该如何异步执行所有操作。有时我想以简单明了的方式做事,这样我就可以继续其他工作了。

由于某种原因,以下代码不起作用。它与我在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

【问题讨论】:

  • 是的,但是,我还希望能够从 Streams 中读取,而不仅仅是文件。我的错,编辑了问题以澄清。
  • @user949300 buffernull 因为还没有可从流中读取的数据。你需要监听readdable事件然后调用rs.read()
  • @Bulkan 但调用 readableStream.on('readable', callback) 是异步的。我希望避免这种情况。
  • @user949300 流本质上是异步的。无法以同步方式使用它们。

标签: javascript node.js


【解决方案1】:

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

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

fs.createReadStream 创建一个ReadStream

【讨论】:

  • 是的,但是,我还希望能够从 Streams 中读取,而不仅仅是文件。我的错,编辑了问题以澄清。
  • @user949300 fs.readSync 在这种情况下可能会有所帮助。
  • 我认为这可以通过 process.stdin.fd 与 stdin 一起使用,但不确定这如何有助于例如来自 HTTP 文件上传的流。
  • @user949300 你得到了同步读取流到字符串的答案吗?
  • @Shubham。不。我重新编写了异步代码,但似乎读取流同步(例如在启动时)仍然很有用
猜你喜欢
  • 2016-03-12
  • 2016-03-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2021-06-11
  • 1970-01-01
  • 2011-11-05
  • 1970-01-01
相关资源
最近更新 更多