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)触发了参数类型错误。
解决步骤
- 添加错误处理逻辑:在
fs.readFile的回调中先判断err是否存在,若存在则返回错误响应,避免使用undefined的data。 - 校验文件路径:确保
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
相关产品推荐
相关产品推荐

