Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

node.js - TypeError when reading files

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");
  });

I'm trying to read the 404 html file whenever I'm accessing a non-specified file in the if(err) condition. The error that I'm getting is TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined. Why do I have this error?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...