如何将使用 fs.readFileSync() 的 Node.js 代码重构为使用 fs.readFile()? [英] How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

查看:29
本文介绍了如何将使用 fs.readFileSync() 的 Node.js 代码重构为使用 fs.readFile()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我尝试像这样重构代码:

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();
    }

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

I get a blank page. I guess it's because it should wait for all the data to be read, before resp.write(data), how do I signal 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();
    });
}

这篇关于如何将使用 fs.readFileSync() 的 Node.js 代码重构为使用 fs.readFile()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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