使用Node.js读取本地HTML文件时出现ERR_INVALID_ARG_TYPE错误的原因?
Node.js读取HTML文件时连接失败并抛出类型错误
问题详情
所有操作在同一台机器上完成(服务器和客户端为同一设备),正在学习Node.js,此前示例均正常运行,但尝试读取HTML文件作为响应内容时出现异常:
- Node.js服务器启动后控制台显示闪烁光标(与正常启动状态一致)
- Chrome访问
localhost:8080时提示“127.0.0.1 拒绝连接” - Node.js控制台抛出类型错误
错误信息
node:_http_outgoing:949 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 write_ (node:_http_outgoing:949:11) at ServerResponse.write (node:_http_outgoing:904:15) at ReadFileContext.callback (C:\path-to-file-omitted\demo_readfile.js:7:9) at FSReqCallback.readFileAfterOpen [as oncomplete] (node:fs:299:13) { code: 'ERR_INVALID_ARG_TYPE' } Node.js v22.13.0
相关代码文件
demofile1.html
<html> <body> <h1>My Header</h1> <p>My paragraph.</p> </body> </html>
demo_readfile.js
var http = require('http'); var fs = require('fs'); http.createServer(function (req, res) { fs.readFile('demofile1.html', function(err, data) { // read the html file res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); // write the html content to the view return res.end(); }); }).listen(8080);
解决方案
核心原因
fs.readFile读取文件失败时(比如文件不存在、路径错误),data参数会是undefined,此时调用res.write(data)就会触发类型错误,导致请求处理中断,浏览器无法获取正常响应。
修改后的代码
添加错误处理逻辑,确保文件读取成功后再返回内容:
var http = require('http'); var fs = require('fs'); http.createServer(function (req, res) { fs.readFile('demofile1.html', function(err, data) { // 优先处理错误场景 if (err) { res.writeHead(404, {'Content-Type': 'text/html'}); res.write('文件未找到'); return res.end(); } // 文件读取成功时返回内容 res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); return res.end(); }); }).listen(8080);
额外检查项
- 确认
demofile1.html与demo_readfile.js在同一目录,或使用文件绝对路径(如C:\your-folder-path\demofile1.html) - 启动命令中的文件路径需正确,示例:
node C:\path-to-file\demo_readfile.js - 若端口8080被占用,可更换端口(比如改成3000,浏览器访问
localhost:3000)
内容的提问来源于stack exchange,提问作者LifeAsPixels
相关产品推荐
相关产品推荐

