Node.js读取HTML文件报ERR_INVALID_ARG_TYPE错误如何解决?
错误原因
- 你当前的代码没有对
fs.readFile的错误参数err做判断,当目标文件./index.html不存在、文件路径填写错误、进程没有该文件的读取权限时,readFile回调的data参数会是undefined - 此时调用
res.write(data)就会传入非法的undefined值,触发ERR_INVALID_ARG_TYPE类型错误
解决方案
- 先确认你的项目运行目录下确实存在名为
index.html的文件,路径和你代码中填写的./index.html完全匹配 - 给
fs.readFile的回调加上错误判断逻辑,出错时返回对应的错误提示,避免传入undefined到res.write - 删掉你代码块末尾多余的英文注释内容,避免语法报错
修正后的完整代码如下:
const http = require('http'); const fs = require('fs'); http.createServer(function (req, res) { //Open a file on the server and return its content: fs.readFile('./index.html', null, (err, data) => { if (err) { res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' }); res.write('文件读取失败,请检查index.html是否存在'); return res.end(); } res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(data); return res.end(); }); }).listen(8080);
内容的提问来源于stack exchange,提问作者tarun pandey
相关产品推荐
相关产品推荐

