簡體   English   中英

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

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

請不要講述我應該如何異步地做所有事情。 有時我想以簡單明了的方式做事,所以我可以繼續其他工作。

由於某種原因,以下代碼不起作用。 它匹配我在最近的SO問題上找到的代碼。 節點改變或破壞了什么?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM