温馨提示×

如何看懂nodejs错误日志

小樊
44
2026-09-11 12:03:56
栏目: 编程语言

看懂 Node.js 错误日志,核心是把**“堆栈信息 + 错误类型 + 触发场景”**对应起来。下面按实用顺序讲。


一、先认识 Node.js 错误日志的基本结构

一个典型错误日志通常包含:

Error: Cannot find module 'express'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:800:15)
    at Function.Module._load (internal/modules/cjs/loader.js:693:27)
    at Module.require (internal/modules/cjs/loader.js:915:19)
    at Object.<anonymous> (/app/index.js:1:1)

关键部分:

  1. 错误类型 + 错误信息
    Error: Cannot find module 'express'
    
  2. 堆栈(stack trace)
    • 从下往上看更接近“你写的代码”
    • 从上往下看是“错误传播路径”
  3. 文件名 + 行号
    /app/index.js:1:1
    
    表示错误源头在 index.js 第 1 行

✅ 经验:先读第一行错误描述,再看最靠近你代码的堆栈行


二、常见 Node.js 错误类型速查

1️⃣ Error: Cannot find module 'xxx'

原因

  • 没安装依赖
  • 路径写错
  • 使用了 ESM 但用了 require

解决

npm install xxx

或检查:

require('./utils') // 是否正确

2️⃣ TypeError: xxx is not a function

原因

  • 变量不是你以为的类型
  • 导入方式错误(默认导出 vs 命名导出)

示例:

import fs from 'fs'
fs.readFileSync() // ✅
import { readFileSync } from 'fs' // ✅

3️⃣ ReferenceError: xxx is not defined

原因

  • 变量没声明
  • 作用域错误

4️⃣ SyntaxError: Unexpected token

原因

  • JS 语法错误
  • ESM / CJS 混用

例如:

import x from 'y' // 但 package.json 没 "type": "module"

5️⃣ ECONNREFUSED / ETIMEDOUT

网络类错误

  • 数据库连接失败
  • 服务没启动

例如:

Error: connect ECONNREFUSED 127.0.0.1:3306

6️⃣ UnhandledPromiseRejectionWarning

原因

  • Promise 没 catch
  • async 函数没 try/catch

✅ 推荐写法:

try {
  await doSomething()
} catch (err) {
  console.error(err)
}

三、如何快速定位问题(实战步骤)

✅ 第一步:看错误“第一行”

人话描述,最重要

✅ 第二步:找你自己的代码行

忽略:

node:internal/...

关注:

your-project/src/xxx.js:12:3

✅ 第三步:确认上下文

问自己:

  • 这一步在干什么?
  • 参数从哪来?
  • 是不是异步问题?

四、让错误日志更好懂的技巧

✅ 1. 用 err.stack

catch (err) {
  console.error(err.stack)
}

✅ 2. 使用日志库

  • winston
  • pino

✅ 3. 开启 source map(TS / 打包项目)

"sourceMap": true

✅ 4. 全局捕获

process.on('uncaughtException', console.error)
process.on('unhandledRejection', console.error)

五、一个真实例子拆解

日志:

TypeError: user.getName is not a function
    at getUser (/app/user.js:10:5)

分析:

  • user 不是你以为的对象
  • 可能:
    • 数据库返回的是 null
    • 接口返回结构变了

✅ 解决:

if (!user || typeof user.getName !== 'function') {
  throw new Error('user 数据异常')
}

六、总结一句话

Node.js 错误日志 = 错误描述 + 调用链 + 你写的代码位置

如果你愿意,可以把一段真实错误日志贴出来,我可以逐行帮你“翻译”。

0 踩