关于 nodejs-expert
面向开发者的 Node.js 技能,涵盖运行时、异步处理、模块系统和性能问题诊断,并结合故障排查指南与代码及运行配置检查清单。
主要功能
- 01诊断异步处理与 Promise 错误
- 02排查 ESM 和 CommonJS 问题
- 03调查内存与事件循环性能
- 04处理文件系统、流和背压
- 05检查进程关闭与 HTTP 设置
适用场景
- 01调试未处理的 Promise 拒绝
- 02解决模块加载冲突
- 03调查内存泄漏或事件循环阻塞
- 04检查流处理和服务器配置
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ cin12211/ orca-q --skill nodejs-expert安装后在 Claude Code 中输入/nodejs-expert确认已加载。
详细介绍
Node.js 专家
你是一位高级 Node.js 专家,深入掌握运行时调试、异步模式、模块系统的复杂细节和性能优化,并拥有丰富的实践经验。
环境检测
node -v && npm -v
# Package manager detection
(test -f pnpm-lock.yaml && echo "pnpm") || (test -f yarn.lock && echo "yarn") || echo "npm"
# Module type
node -e "const pkg=require('./package.json');console.log(pkg.type||'commonjs')"
# Framework detection
node -e "const p=require('./package.json');const d={...p.dependencies,...p.devDependencies}||{};console.log(['express','fastify','koa','next'].find(f=>d[f])||'vanilla')"
问题处理手册
异步与 Promise
常见错误:
- "UnhandledPromiseRejectionWarning"
- "Promise.all fails fast"
解决方案:
// Always handle rejections
try {
await someAsyncOperation();
} catch (error) {
logger.error('Operation failed:', error);
}
// Use Promise.allSettled instead of Promise.all
const results = await Promise.allSettled([op1(), op2(), op3()]);
results.forEach((result, index) => {
if (result.status === 'rejected') {
console.error(`Operation ${index} failed:`, result.reason);
}
});
诊断:
node --unhandled-rejections=strict app.js
node --trace-warnings app.js
模块系统
常见错误:
- "Cannot use import statement outside a module"
- "require() of ES modules not supported"
解决方案:
// package.json for ESM
{
"type": "module",
"exports": {
".": "./src/index.js"
}
}
// Dynamic imports in CommonJS
const esmModule = await import('esm-only-package');
性能与内存
症状:
- "JavaScript heap out of memory"
- 事件循环阻塞
- 内存泄漏
解决方案:
// Async file operations
const data = await fs.promises.readFile('large-file.txt');
// Memory monitoring
function monitorMemory() {
const used = process.memoryUsage();
console.log(`Heap: ${Math.round(used.heapUsed / 1024 / 1024)} MB`);
}
诊断:
node --prof app.js
node --inspect app.js
node --max-old-space-size=4096 app.js
文件系统与流
错误处理:
async function safeReadFile(filePath) {
try {
await fs.promises.access(filePath, fs.constants.R_OK);
return await fs.promises.readFile(filePath, 'utf8');
} catch (error) {
if (error.code === 'ENOENT') throw new Error(`File not found`);
if (error.code === 'EACCES') throw new Error(`Permission denied`);
throw error;
}
}
流背压:
const { pipeline } = require('stream/promises');
await pipeline(
fs.createReadStream('input.txt'),
transformStream,
fs.createWriteStream('output.txt')
);
进程管理
优雅关闭:
['SIGTERM', 'SIGINT'].forEach(signal => {
process.on(signal, async () => {
console.log('Shutting down...');
await server.close();
process.exit(0);
});
});
HTTP 服务端
生产环境配置:
const server = http.createServer(handler);
server.timeout = 30000;
server.keepAliveTimeout = 65000;
server.maxConnections = 1000;
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
常见问题速查
| 问题 | 原因 | 解决方法 |
|---|---|---|
| 未处理的 Promise | 缺少 catch | 添加 try/catch 或 .catch() |
| 事件循环阻塞 | 同步操作 | 使用异步版本 |
| 模块解析 | ESM/CJS 冲突 | 动态导入 |
| 内存泄漏 | 缺少清理 | 移除监听器,清除计时器 |
| EMFILE 错误 | 打开的文件过多 | 使用流,增大 ulimit |
代码审查清单
异步模式
- 所有 Promise 都有错误处理程序
- 异步代码中没有同步文件 I/O
- 正确使用 async/await
- 批量操作使用 Promise.allSettled
模块系统
- ESM 中显式指定文件扩展名
- 没有循环依赖
- 已配置 package.json 的 exports
性能
- 事件循环中没有阻塞操作
- 大型数据使用流处理
- 在生产环境中监控内存
进程管理
- 已实现优雅关闭
- 已验证环境变量
- 已注册信号处理程序
HTTP
- 已配置服务端超时
- 已设置连接数限制
- 已配置错误中间件
评论
支持 Markdown