readFile() 和 readFileSync() 的区别 [英] Difference between readFile() and readFileSync()

查看:31
本文介绍了readFile() 和 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆