readFile和readFileSync之间的区别 [英] Difference between readFile and readFileSync

查看:1546
本文介绍了readFile和readFileSync之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将index.html的内容(它只包含文本hello world)输出到浏览器。但是,当我用readFileSync替换readFile时,请求超时。我错过了什么?是否需要不同类型的缓冲区?我使用节点0.61并表达2.4

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. 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.

如果你需要显示你的readFileSync代码'不仅仅是用readFileSync替换readFile。

You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.

另外,你知道,你应该永远在一个节点中调用readFileSync / webserver因为它会在执行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天全站免登陆