const http = require("http");
const url = require("url");
const fs = require("fs");
http
.createServer(function (req, res) {
const pathname = url.parse(req.url, true).pathname;
if (pathname == "/favicon.ico") return res.end();
let filename;
if (pathname == "/") filename = "./index.html";
else filename = "." + pathname + ".html";
console.log(filename);
fs.readFile(filename, function (err, data) {
if (err) {
fs.readFile("./404.html", function (err, data) {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
return res.end();
});
}
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
return res.end();
});
})
.listen(8080, () => {
console.log("Server made");
});
每当我在 if(err) 条件下访问未指定的文件时,我都会尝试读取 404 html 文件。我得到的错误是 TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
。为什么会出现这个错误?