你如何在node.js中同步读取文件或流? [英] How do you read a file or Stream synchronously in node.js?
本文介绍了你如何在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.
由于某种原因,以下代码不起作用。它匹配我在最近的SO问题上找到的代码。节点是否改变或破坏了什么?
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?
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,我看到
Looking at rs in the debugger, I see
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
To read the contents of a file synchronously use fs.readFileSync
var fs = require('fs');
var content = fs.readFileSync('myfilename');
console.log(content);
fs.createReadStream 创建 ReadStream 。
这篇关于你如何在node.js中同步读取文件或流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文