Node.js 从 fs.readFileSync() 到 fs.readFile()

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

Node.js from fs.readFileSync() to fs.readFile()

node.jscallbackreadfilefs

提问by Bondifrench

I'm trying to get my head around synchronous vs asynchronous in Node.js, in particular for reading an html file.

我正在尝试了解 Node.js 中的同步与异步,尤其是读取 html 文件。

In a request handler, the synchronous version that i'm using, which works is the following:

在请求处理程序中,我正在使用的同步版本如下所示:

var fs = require("fs");
var filename = "./index.html";
var buf = fs.readFileSync(filename, "utf8");

function start(resp) {
    resp.writeHead(200, {"Content-type":"text/html"});
    resp.write(buf);
    resp.end();
    }

exports.start=start; 
  1. What would be the version using readFile() ??
  2. I understand that readFile is asynchronous so theoretically I should wait that the entire file is read before rendering it, so should I introduce an addListener? I might be confusing different things.
  1. 使用 readFile() 的版本是什么??
  2. 我知道 readFile 是异步的,所以理论上我应该在渲染之前等待整个文件被读取,所以我应该引入一个 addListener 吗?我可能会混淆不同的东西。

Edit: I have tried to refactor the code like this:

编辑:我试图重构这样的代码:

var fs = require("fs");
var filename = "./index.html";
function start (resp) {
    resp.writeHead(200, {"Content-Type":"text/html"});
    fs.readFile(filename, "utf8", function (err, data) {
        if (err) throw err;
        resp.write(data);
        });
    resp.end();
    }

I get a blank page, I guess it's because it should wait that all the data has been read, before resp.write(data), how do i signal this?

我得到一个空白页,我想这是因为它应该等待所有数据都被读取,然后在 resp.write(data) 之前,我该如何发出信号?

采纳答案by webduvet

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}

回答by Akhmedzianov Danilian

This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

这种变体更好,因为您无法知道文件是否存在。当您确定可以读取文件内容时,您应该发送正确的标题。此外,如果您的代码分支没有以 '.end()' 结束,浏览器将等到它得到它们。换句话说,您的浏览器将等待很长时间。

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}