node.js fs.read() 示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5985748/
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
node.js fs.read() example
提问by Gert Cuykens
app=function(req,res)
{
res.writeHead(200,{'Content-Type':'text/plain'})
var buffer=new Buffer(100)
var fs=require('fs')
fs.open('.'+req.url,'r',function(err,fd){
fs.fstat(fd,function(err, stats){
var i=0
var s=stats.size
console.log('.'+req.url+' '+s)
for(i=0;i<s;console.log(i)){
i=i+buffer.length
fs.read(fd,buffer,0,buffer.length,i,function(e,l,b){
res.write(b.toString('utf8',0,l))
console.log(b.toString('utf8',0,l))
})
}
res.end()
fs.close(fd)
})
})
}
http = require('http')
server = http.createServer(app)
server.listen(8000,"127.0.0.1")
console.log('GET http://127.0.0.1:8000/appwsgi/www/index.htm')
Why does this only show the last 100 bytes multiple times from a 979 bytes file?
为什么这只会多次显示 979 字节文件中的最后 100 字节?
Why does chrome browser not show any output?
为什么 chrome 浏览器不显示任何输出?
gert@node:~/http$ node server.js
GET http://127.0.0.1:8000/appwsgi/www/index.htm
./appwsgi/www/index.htm 979
100
200
300
400
500
600
700
800
900
1000
"vi/vi.htm">vi</a> Edit online files on the server.
</div>
</body>
</html>
oad.<br/>
<a href=
"vi/vi.htm">vi</a> Edit online files on the server.
</div>
</body>
</html>
oad.<br/>
<a href=
"vi/vi.htm">vi</a> Edit online files on the server.
</div>
</body>
</html>
oad.<br/>
<a href=
"vi/vi.htm">vi</a> Edit online files on the server.
</div>
</body>
</html>
oad.<br/>
<a href=
"vi/vi.htm">vi</a> Edit online files on the server.
</div>
</body>
</html>
oad.<br/>
<a href=
"vi/vi.htm">vi</a> Edit online files on the server.
</div>
</body>
</html>
oad.<br/>
<a href=
"vi/vi.htm">vi</a> Edit online files on the server.
</div>
</body>
</html>
oad.<br/>
<a href=
"vi/vi.htm">vi</a> Edit online files on the server.
</div>
</body>
</html>
oad.<br/>
<a href=
"vi/vi.htm">vi</a> Edit online files on the server.
</div>
</body>
</html>
采纳答案by Geoff Chappell
All of the reads are issued asynchronously using the same buffer (i.e. fs.read returns immediately and the loop continues). By the time the async callback is called the first time, apparently all ten reads have completed (so the buffer contains the results of the last read). Since you called fs.read 10 times, you'll get called back 10 times. So you get what you see.
所有读取都使用相同的缓冲区异步发出(即 fs.read 立即返回并且循环继续)。到第一次调用异步回调时,显然所有十次读取都已完成(因此缓冲区包含最后一次读取的结果)。由于您调用了 fs.read 10 次,因此您将被调用 10 次。所以你得到你所看到的。
The browser shows nothing because you've ended the response before the first callback returns.
浏览器什么都不显示,因为您在第一个回调返回之前结束了响应。
回答by Joshua Davison
I know this question is not the newest, but I'm going to chuck this up here because when I was getting issues how to open (and read) a filesystem object, a quick search always seemed to direct me here.
我知道这个问题不是最新的,但我将把它抛在这里,因为当我遇到如何打开(和读取)文件系统对象的问题时,快速搜索似乎总是将我引导到这里。
Anyhow, this should help with the OP, and others in the future.
无论如何,这应该对 OP 和未来的其他人有所帮助。
(filepath is the actual filename, including path)
(filepath 是实际的文件名,包括路径)
fs.open(filepath, 'r', function(err, fd) {
fs.fstat(fd, function(err, stats) {
var bufferSize=stats.size,
chunkSize=512,
buffer=new Buffer(bufferSize),
bytesRead = 0;
while (bytesRead < bufferSize) {
if ((bytesRead + chunkSize) > bufferSize) {
chunkSize = (bufferSize - bytesRead);
}
fs.read(fd, buffer, bytesRead, chunkSize, bytesRead);
bytesRead += chunkSize;
}
console.log(buffer.toString('utf8', 0, bufferSize));
fs.close(fd);
});
});
回答by simo
I used the @user1256169 example from above to create what I needed. Here I'm using async.whilstto handle the async control flow more cleanly. At the top of the example I'm reading the file and its stats synchronously, but that can be changed if there is a need to.
我使用上面的@user1256169 示例来创建我需要的内容。这里我使用async.while来更干净地处理异步控制流。在示例的顶部,我正在同步读取文件及其统计信息,但如果需要,可以更改。
var fs = require('fs');
var async = require('async');
var fd = fs.openSync('/path/to/cat.png', 'r');
var stats = fs.fstatSync(fd);
var bufferSize = stats.size,
chunkSize = 512,//bytes
buffer = new Buffer(bufferSize),
bytesRead = 0;
async.whilst(
function () {
return bytesRead < bufferSize;
},
function (done) {
if ((bytesRead + chunkSize) > bufferSize) {
chunkSize = (bufferSize - bytesRead);
}
// fd, buffer, offset, length, position, callback
fs.read(fd, buffer, bytesRead, chunkSize, bytesRead,
function (err, bytes, buff) {
if (err) return done(err);
var buffRead = buff.slice(bytesRead, bytesRead+chunkSize);
// do something with buffRead
bytesRead += chunkSize;
done();
});
},
function (err) {
if (err) console.log(err);
fs.close(fd);
}
);
回答by Rob Raisch
Since you've designed your app to process files one after another (synchronously), you need to use fs.readSync() but be warned that, while your app is reading a file in this way, it cannot do anything else.
由于您将应用程序设计为一个接一个(同步)处理文件,因此您需要使用 fs.readSync() 但请注意,当您的应用程序以这种方式读取文件时,它无法执行任何其他操作。
A better approach would be to process the files in the "node way", that is asynchronously.
更好的方法是以“节点方式”处理文件,即异步处理。
-- node.fs - one line, no waiting
-- node.fs - 一行,无需等待

