本文介绍了Node.js从fs.readFileSync()到fs.readFile()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在一个请求处理程序中,同步(同步)我使用的版本,其工作原理如下:
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?我可能会混淆不同的事情。
编辑:我试图重构代码如下:
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)之前,我该如何发出信号?
解决方案
var fs = requires(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'm trying to get my head around synchronous vs 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;
- What would be the version using readFile() ??
- 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.
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?
解决方案
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();
});
}
这篇关于Node.js从fs.readFileSync()到fs.readFile()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!