下面给出 最简可运行 的 TypeScript Web 服务端示例:
- 使用 ES Module
- 仅依赖 Node.js 标准库(零第三方包)
- 支持 GET
/?file=xxx返回对应文件内容
📁 0️⃣ 项目初始化
mkdir ts-web && cd ts-web
npm init -y
npm install typescript --save-dev
npm install @types/node --save-dev
npm install tsx --save-dev
📁 1️⃣ 目录结构
ts-web/
├─ package.json
├─ tsconfig.json
└─ src/
└─ server.ts
📄 2️⃣ 文件内容
package.json
{
"name": "ts-web",
"type": "module",
"scripts": {
"dev": "tsx src/server.ts"
},
"devDependencies": {
"@types/node": "^22.0.0",
"tsx": "^4.20.4",
"typescript": "^5.9.2"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "node",
"strict": true
}
}
src/server.ts
import { createServer } from 'http';
import { readFileSync } from 'fs';
import { join } from 'path';
import { URL } from 'url';
const port = 3000;
const server = createServer((req, res) => {
// 解析 URL 获取 ?file=xxx
const { searchParams } = new URL(req.url!, `http://${req.headers.host}`);
const fileName = searchParams.get('file');
if (!fileName) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Missing ?file= parameter');
return;
}
try {
// 安全:只允许读取当前目录下的文件
const safePath = join(process.cwd(), fileName);
console.log(`safePath=${safePath}=`)
const content = readFileSync(safePath, 'utf8');
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(content);
} catch (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end(`${fileName} File not found`);
}
});
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
🚀 3️⃣ 运行(2 条命令)
# 1) 安装依赖
npm install
# 2) 启动服务
npm run dev
🧪 4️⃣ 测试
浏览器或 curl 访问:
http://localhost:3000/?file=src/server.ts
即可看到 server.ts 的源代码内容。