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

Node.js运行W3School fs模块示例报ERR_INVALID_ARG_TYPE错误

问题现象

运行Node.js文件系统模块相关示例代码时,在Node.js v18.3.0环境下抛出如下类型错误:

node:_http_outgoing:791
throw new ERR_INVALID_ARG_TYPE(
^

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
    at new NodeError (node:internal/errors:377:5)
    at write_ (node:_http_outgoing:791:11)
    at ServerResponse.write (node:_http_outgoing:756:15)
at ReadFileContext.callback (C:\Proyectos\myfirst.js:6:9)
    at FSReqCallback.readFileAfterOp

报错核心为:传入res.write()的参数为undefined,不符合方法要求的字符串、Buffer或Uint8Array类型。

复现代码

服务端代码(myfirst.js)

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文件(demofile1.html)

<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
故障原因
  • 代码中使用相对路径demofile1.html读取文件时,Node.js会以执行node命令时的终端工作目录为基准解析路径,而非myfirst.js文件自身所在的目录。如果执行命令时终端路径不匹配,会直接导致文件读取失败,此时回调参数data为undefined。
  • 原代码未对fs.readFile的错误分支做处理,文件读取失败后依然直接执行res.write(data),最终触发类型错误。
修复方案
  • 临时修复:执行node命令前,先通过cd命令切换终端工作目录到myfirst.js、demofile1.html共同存放的目录,再运行启动命令。
  • 稳定修复(推荐):使用Node.js全局变量__dirname拼接文件的绝对路径,同时补充错误处理逻辑,修改后的服务端代码如下:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  // 基于当前js文件所在目录的绝对路径拼接html文件路径
  fs.readFile(__dirname + '/demofile1.html', function(err, data) {
    // 优先处理读文件错误
    if (err) {
      res.writeHead(500, {'Content-Type': 'text/plain'});
      res.end('Server error: read file failed');
      return;
    }
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

修改后无论在哪个目录下执行启动命令,都能准确定位到目标html文件,读文件出错时也会返回明确提示,不会抛出类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 22:27:20