You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js读取HTML文件报ERR_INVALID_ARG_TYPE错误如何解决?

错误原因
  • 你当前的代码没有对fs.readFile的错误参数err做判断,当目标文件./index.html不存在、文件路径填写错误、进程没有该文件的读取权限时,readFile回调的data参数会是undefined
  • 此时调用res.write(data)就会传入非法的undefined值,触发ERR_INVALID_ARG_TYPE类型错误
解决方案
  1. 先确认你的项目运行目录下确实存在名为index.html的文件,路径和你代码中填写的./index.html完全匹配
  2. 给fs.readFile的回调加上错误判断逻辑,出错时返回对应的错误提示,避免传入undefined到res.write
  3. 删掉你代码块末尾多余的英文注释内容,避免语法报错

修正后的完整代码如下:

const http = require('http');
const fs = require('fs');

http.createServer(function (req, res) {
  //Open a file on the server and return its content:
  fs.readFile('./index.html', null, (err, data) => {
      if (err) {
        res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' });
        res.write('文件读取失败,请检查index.html是否存在');
        return res.end();
      }
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.write(data);
      return res.end();
    });
}).listen(8080);

内容的提问来源于stack exchange,提问作者tarun pandey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 02:54:07