node.js readFile 和 readFileSync 之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17604866/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:00:39  来源:igfitidea点击:

Difference between readFile and readFileSync

javascriptnode.jsexpress

提问by Ali

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

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

回答by bryanmac

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

fs.readFile接受一个回调,该回调调用 response.send,如您所示 - 很好。如果你简单地用fs.readFileSync替换它,你需要注意它不接受回调,所以你调用 response.send 的回调永远不会被调用,因此响应永远不会结束,它会超时。

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

如果您不是简单地用 readFileSync 替换 readFile,则需要显示您的 readFileSync 代码。

Also, just so you're aware, you should nevercall 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.

此外,正如您所知,您永远不应该在节点 express/webserver 中调用 readFileSync,因为它会在执行 I/O 时占用单线程循环。您希望节点循环处理其他请求,直到 I/O 完成并且您的回调处理代码可以运行。

回答by Saurabh Chauhan

'use strict'
var fs = require("fs");

/***
 * implementation of readFileSync
 */
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");

/***
 * implementation of readFile 
 */
fs.readFile('input.txt', function (err, data) {
    if (err) return console.error(err);
   console.log(data.toString());
});

console.log("Program Ended");

For better understanding run the above code and compare the results..

为了更好地理解运行上面的代码并比较结果..

回答by Paresh Barad

readFileSync()is synchronous and blocks execution until finished. These return their results as return values. readFile()are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish. let's take an example for non-blocking.

readFileSync()是同步的并阻止执行直到完成。这些将它们的结果作为返回值返回。 readFile()是异步的,并在它们在后台运行时立即返回。您传递一个回调函数,该函数在完成时被调用。让我们举一个非阻塞的例子。

following method read a file as a non-blocking way

以下方法以非阻塞方式读取文件

var fs = require('fs');
fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        console.log(data);
});

following is read a file as blocking or synchronous way.

以下是以阻塞或同步方式读取文件。

var data = fs.readFileSync(filename);

LOL...If you don't want readFileSync()as blocking way then take reference from the following code. (Native)

大声笑...如果你不想要readFileSync()阻塞方式,那么请参考以下代码。(本国的)

var fs = require('fs');
function readFileAsSync(){
    new Promise((resolve, reject)=>{
        fs.readFile(filename, "utf8", function(err, data) {
                if (err) throw err;
                resolve(data);
        });
    });
}

async function callRead(){
    let data = await readFileAsSync();
    console.log(data);
}

callRead();

it's mean behind scenes readFileSync()work same as above(promise) base.

这意味着幕后readFileSync()工作与上述(承诺)基础相同。