如何将使用fs.readFileSync()的Node.js代码重构为使用fs.readFile()? [英] How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?
本文介绍了如何将使用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.
在请求处理程序中,我所使用的同步版本m使用,其工作原理如下:
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;
- 使用
readFile()的版本是什么
? - 我知道
readFile
是异步的,因此从理论上讲,我应该等待整个文件读取后再渲染它,所以我应该介绍一个addListener
吗?我可能会混淆其他事情。
- What would be the version using
readFile()
? - 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 anaddListener
? 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屋!
查看全文