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

Node.js读取HTML文件出现ERR_INVALID_ARG_TYPE错误的解决方法

Node.js读取HTML文件展示报错的修复方案

问题场景

编写了以下Node.js代码,尝试读取本地demofile1.html文件并通过HTTP服务器展示:

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
    fs.readFile('demofile1.html', function (err, data) {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(data);
        return res.end();
    });
}).listen(8080);

对应的HTML文件内容:

<html>

<body>
    <h1>My Header</h1>
    <p>My paragraph.</p>
</body>

</html>

运行时触发错误:

The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
at new NodeError (node:internal/errors:399:5)
at write_ (node:_http_outgoing:872:11)
at ServerResponse.write (node:_http_outgoing:831:15)
at ReadFileContext.callback(C:\Users\ASUS\OneDrive\Máy tính\Nodejs\myfirst.js:6:13)
at FSReqCallback.readFileAfterOpen [as oncomplete] (node:fs:325:13) {
code: 'ERR_INVALID_ARG_TYPE'
}

错误原因

这个错误本质是**fs.readFile读取文件失败时,data参数为undefined,但代码未处理错误就直接将undefined传给res.write()**,导致参数类型不符合要求。常见的读取失败原因包括:

  • demofile1.html文件不存在
  • 文件路径错误(比如相对路径指向的目录不对)
  • 没有文件读取权限

修复方案

在fs.readFile的回调函数中先处理错误,再返回正常内容:

修复后的代码

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
    fs.readFile('demofile1.html', function (err, data) {
        // 先判断是否有读取错误
        if (err) {
            // 返回500错误和错误信息
            res.writeHead(500, { 'Content-Type': 'text/plain' });
            res.write('文件读取失败: ' + err.message);
            return res.end();
        }
        // 读取成功时返回文件内容
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(data);
        return res.end();
    });
}).listen(8080);

额外注意事项

  1. 确认文件路径:确保demofile1.html和Node.js脚本文件在同一目录下;如果不在同一目录,使用绝对路径(比如C:\Users\ASUS\OneDrive\Máy tính\Nodejs\demofile1.html)或者正确的相对路径。
  2. 权限检查:确保Node.js进程有读取该文件的权限。

内容的提问来源于stack exchange,提问作者Duy Bảo Trần

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 04:52:29