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

使用tsx运行基础Express服务器出现内存不足错误

tsx运行Express服务器内存异常飙升的解决办法

问题复现

运行极简Express TypeScript服务器时,使用tsx server.ts启动会导致Node进程内存占用迅速突破8GB并启用交换空间,但编译为JS后用node server.js或node dist/server.js启动时内存占用低于200MB,设置--max-old-space-size=4096也无法缓解,且所有通过tsx运行的应用都存在此问题。

服务器代码:

import express from 'express';

const app = express();

app.get('/', (req, res) => {
    if (req.query.name) {
        res.send(`Hello ${req.query.name}`);
    } else {
        res.send('Hello World');
    }
});

app.listen(3000, () => {
    console.log('Server started')
});

排查与解决步骤

1. 检查并调整tsx版本

tsx部分版本存在内存泄漏或资源占用异常的bug,先确认当前版本:

tsx --version

尝试升级到最新稳定版或降级到已知无问题的版本:

# 升级到最新版
npm install tsx@latest -D

# 或降级到指定稳定版,比如3.12.7
npm install tsx@3.12.7 -D

2. 禁用tsx缓存功能

tsx默认启用编译缓存,若缓存逻辑异常可能导致内存暴涨,启动时添加--no-cache参数:

tsx --no-cache server.ts

3. 排查Node.js版本兼容性

确保使用的Node.js版本为LTS版本(如18.x、20.x),过新或过旧的Node版本可能与tsx存在兼容性问题,切换后重新测试。

4. 避免全局与本地tsx版本冲突

若同时安装了全局和项目本地的tsx,可能因版本不一致引发异常,优先使用项目本地依赖运行:

npx tsx server.ts

或卸载全局tsx:

npm uninstall tsx -g

5. 简化tsconfig.json配置

复杂的TypeScript编译配置可能导致tsx转译时消耗过量内存,临时使用极简配置测试:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "strict": false
  },
  "include": ["server.ts"]
}

6. 替换为其他TypeScript运行时验证

使用ts-node等替代工具测试,确认问题是否为tsx独有:

ts-node server.ts

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 02:42:10