我已经使用fs.readFileSync()
来读取HTML文件,并且可以正常工作。但是当我使用fs.readFile()
时出现问题。您能帮我解决问题吗?任何帮助将不胜感激!
fs.readFileSync()
:const http = require("http");
const fs = require("fs");
http.createServer((req, res) => {
res.writeHead(200, {
"Content-type": "text/html"
});
const html = fs.readFileSync(__dirname + "/bai55.html", "utf8");
const user = "Node JS";
html = html.replace("{ user }", user);
res.end(html);
}).listen(1337, "127.0.0.1");
fs.readFileSync code>”>] >>
fs.readFile()
。为什么无法读取HTML文件?const http = require("http"); const fs = require("fs"); http.createServer((req, res) => { res.writeHead(200, { "Content-type": "text/html" }); const html = fs.readFile(__dirname + "/bai55.html", "utf8"); const user = "Node JS"; html = html.replace("{ user }", user); res.end(html); }).listen(1337, "127.0.0.1");
fs.readFile() code >>]
我已经使用fs.readFileSync()读取HTML文件,并且可以正常工作。但是我在使用fs.readFile()时遇到问题。您能帮我解决问题吗?任何帮助将不胜感激!使用fs ....
这与Node.js的基本概念有关:异步I / O操作。这意味着在执行I / O时,程序可以继续执行。文件中的数据准备就绪后,将通过回调中的代码对其进行处理。换句话说,该函数不返回值,而是在其最后一个操作执行回调时传递所检索的数据或错误。这是Node.js中的常见范例,也是处理异步代码的常见方法。正确调用fs.readFile()
如下所示:
由于readFile使用回调,并且不立即返回数据。
可以通过杠杆Promise
来解决此问题>
const fs = require('fs');
const http = require("http");
const fsReadFileHtml = (fileName) => {
return new Promise((resolve, reject) => {
fs.readFile(path.join(__dirname, fileName), 'utf8', (error, htmlString) => {
if (!error && htmlString) {
resolve(htmlString);
} else {
reject(error)
}
});
});
}
http.createServer((req, res) => {
fsReadFileHtml('bai55.html')
.then(html => {
res.writeHead(200, {
"Content-type": "text/html"
});
res.end(html.replace("{ user }", "Node JS"));
})
.catch(error => {
res.setHeader('Content-Type', 'text/plain');
res.end(`Error ${error}`);
})
}).listen(1337, "127.0.0.1");