在本教程中http://www.dotnetcurry.com/nodejs/1270/read-html-file-and-send-html-response-nodejs
//1.
var http = require('http');
var fs = require('fs');
//2.
var server = http.createServer(function (req, resp) {
//3.
if (req.url === "/create") {
fs.readFile("AppPages/MyPage.html", function (error, pgResp) {
if (error) {
resp.writeHead(404);
resp.write('Contents you are looking are Not Found');
} else {
resp.writeHead(200, { 'Content-Type': 'text/html' });
resp.write(pgResp);
}
resp.end();
});
} else {
//4.
resp.writeHead(200, { 'Content-Type': 'text/html' });
resp.write('<h1>Product Manaager</h1><br /><br />To create product please enter: ' + req.url);
resp.end();
}
});
//5.
server.listen(5050);
我不明白,因为 readFile 是异步的,如果页面需要很长时间加载,为什么它会可靠地工作?那么这里是否需要 readSync 或者即使文件非常大也允许等待页面被完全读取?
它工作正常,因为在 readFile 的参数中定义的函数(该函数称为回调函数 btw)仅在文件已被读取时才会执行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句