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

Node.js中node:_http_outgoing:862错误及fs模块失效问题求助

Node.js 服务器报错 ERR_INVALID_ARG_TYPE 排查与解决

错误信息

node:_http_outgoing:862
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:399:5)
at write_ (node:_http_outgoing:862:11)
at ServerResponse.write (node:_http_outgoing:827:15)
at ReadFileContext.callback (c:\Users\me\Documents\Web Devolopment Challenge\intro\sample-server.js:7:9)
at FSReqCallback.readFileAfterOpen [as oncomplete] (node:fs:324:13) {
code: 'ERR_INVALID_ARG_TYPE'
}

Node.js v18.14.1

用户代码

Node.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(7000);

HTML 文件代码(demofile1.html)

<html>
    <h1>hello guys</h1>
    <h2>heyy</h2>
</html>

问题原因

报错核心是res.write(data)中的data为undefined,这是因为fs.readFile读取文件失败时(比如文件不存在、路径错误、权限不足),回调函数的data参数会是undefined,而代码未处理错误情况,直接执行res.write(data)触发了参数类型错误。

解决步骤

  1. 添加错误处理逻辑:在fs.readFile的回调中先判断err是否存在,若存在则返回错误响应,避免使用undefined的data。
  2. 校验文件路径:确保demofile1.html和sample-server.js在同一目录下,或使用绝对路径定位文件。

改进后的代码

var http = require('http')
var fs = require('fs')
var path = require('path')

http.createServer(function (req, res) {
  // 使用绝对路径确保文件能被正确找到
  const filePath = path.join(__dirname, 'demofile1.html')
  fs.readFile(filePath, function(err, data) {
    if (err) {
      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(7000);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:46:18