readFile()和readFileSync()之间的区别 [英] Difference between readFile() and readFileSync()
问题描述
以下代码将index.html的内容(它仅包含文本hello world)输出到浏览器.但是,当我用readFileSync()
替换readFile()
时,请求超时.
The following code outputs the content of the index.html (it just contains the text hello world) to the browser. However, when I replace readFile()
with readFileSync()
, the request times out.
我想念什么?是否需要其他类型的缓冲区?我正在使用节点0.61并表示2.4.
What am I missing? Is a different kind of buffer required? I am using node 0.61 and express 2.4.
var express = require('express');
var fs = require('fs');
var app = express.createServer(express.logger());
app.get('/', function(request, response) {
fs.readFile('index.html', function(err, data){
response.send(data.toString());
});
});
var port = process.env.PORT || 5000;
app.listen(port, function() {
console.log("Listening on " + port);
});
推荐答案
fs.readFile 进行回叫,如您所显示的那样调用response.send-很好.如果您只是将其替换为 fs.readFileSync ,则需要注意一个回调,这样您的调用response.send的回调将永远不会被调用,因此响应将永远不会结束并且会超时.
fs.readFile takes a call back which calls response.send as you have shown - good. If you simply replace that with fs.readFileSync, you need to be aware it does not take a callback so your callback which calls response.send will never get called and therefore the response will never end and it will timeout.
如果您不只是将readFile替换为readFileSync,则需要显示readFileSync代码.
You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.
也请注意,您应该从不永远不要在节点express/webserver中调用readFileSync,因为它会在执行I/O时阻塞单线程循环.您希望节点循环能够处理其他请求,直到I/O完成并且您的回调处理代码可以运行为止.
Also, just so you're aware, you should never call readFileSync in a node express/webserver since it will tie up the single thread loop while I/O is performed. You want the node loop to process other requests until the I/O completes and your callback handling code can run.
这篇关于readFile()和readFileSync()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!