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

Node.js HTTPS服务器崩溃:fs.readFile()路径undefined问题排查

问题分析与解决方案

核心问题

你遇到的ERR_INVALID_ARG_TYPE错误和event loop无关,根源是两个代码逻辑漏洞:

  1. 未处理非根路径请求:浏览器访问根路径/时,会自动额外发起/favicon.ico请求(用于获取网站图标),此时req.url不是/,resource变量未被赋值,保持undefined,传给fs.readFile就触发了参数类型错误。
  2. 缺失错误处理逻辑:即使resource赋值成功,fs.readFile也可能出现文件不存在、权限不足等错误,当前代码直接忽略err参数,会导致后续res.write(data)因data为undefined引发崩溃。

修正后的代码

const https = require('https');
const fs = require('fs');
const path = require("path");

const options = {
    key: fs.readFileSync(path.resolve(__dirname, 'key.pem')),
    cert: fs.readFileSync(path.resolve(__dirname, 'cert.pem')),
};

https
    .createServer(options, (req, res) => {
        let resource;
        switch (req.url) {
            case '/': {
                resource = path.resolve(__dirname, '..', 'dist/index.html');
                break;
            }
            // 处理浏览器自动发起的图标请求
            case '/favicon.ico': {
                res.writeHead(404);
                res.end();
                return; // 提前结束,避免执行后续文件读取逻辑
            }
            default: {
                // 所有未匹配的请求返回404
                res.writeHead(404, { 'Content-Type': 'text/plain' });
                res.write('404 Not Found');
                res.end();
                return;
            }
        } 
        fs.readFile(resource, (err, data) => {
            if (err) {
                // 处理文件读取错误,返回服务器内部错误响应
                res.writeHead(500, { 'Content-Type': 'text/plain' });
                res.write('Server Error: ' + err.message);
                res.end();
                return;
            }
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.write(data);
            res.end();
        });
    })
    .listen(8080, () => console.log('Server is running. Yes.'));

关键改进点

  • 新增default分支和/favicon.ico分支,确保所有请求都能被处理,彻底避免resource为undefined的情况。
  • 在fs.readFile回调中优先判断err,及时返回错误响应,防止后续逻辑因错误导致崩溃。
  • 针对不同场景返回正确的HTTP状态码(404表示资源不存在,500表示服务器内部错误),符合HTTP规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:10:48