Node.js游戏服务器项目移植-2: 用TypeScript还是Javascript

nodejs服务器不仅仅可以使用javascript作为开发语言,也可以使用typescript。这里用ts实现一个简单的 城市人口查询服务器 作为例子

一、先安装依赖(TS 版)

bash

运行

复制代码
npm init -y
npm install express
npm install -D typescript @types/express @types/node ts-node

二、创建 tsconfig.json

json

复制代码
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*"]
}

三、完整 TypeScript 代码(2 个文件)

src/PopulationSearch.ts

typescript

运行

复制代码
// 城市人口查询类(TS 版)
export class PopulationSearch {
  // 静态变量
  static callNum = 0;
  static notifyNumEvent?: (count: number) => void;

  // 成员变量
  private cityName = "";

  async search(cityName: string) {
    this.cityName = cityName;
    console.log("将要查询人口的城市是:" + cityName);

    // 模拟城市人口数据
    const populationData: Record<string, number> = {
      "北京": 2154,
      "上海": 2428,
      "广州": 1530,
      "深圳": 1756,
      "杭州": 981,
      "成都": 1658,
      "重庆": 3212,
    };

    if (!populationData[cityName]) {
      throw new Error("暂无该城市人口数据");
    }

    // 计数 + 触发事件
    PopulationSearch.callNum++;
    PopulationSearch.notifyNumEvent?.(PopulationSearch.callNum);

    return {
      city: cityName,
      population: populationData[cityName],
      year: 2024,
      unit: "万人"
    };
  }
}

src/index.ts(主服务)

typescript

运行

复制代码
import { PopulationSearch } from "./PopulationSearch";
import express from "express";

const app = express();

// 业务方法
async function run(cityName: string) {
  try {
    const service = new PopulationSearch();
    return await service.search(cityName);
  } catch (err) {
    console.error("错误:", err);
    return null;
  }
}

// 统计回调
PopulationSearch.notifyNumEvent = (count) => {
  console.log(`恭喜,API被调用了 ${count} 次,可喜可贺!`);
};

// Express 5 接口(async 直接支持)
app.get("/search/:cityName", async (req, res) => {
  const cityName = req.params.cityName;
  const data = await run(cityName);

  if (data) {
    res.json(data);
  } else {
    res.status(404).json({ error: "未找到该城市人口数据" });
  }
});

// 错误处理
app.use((err: Error, req: express.Request, res: express.Response) => {
  console.error("服务器异常:", err);
  res.status(500).json({ error: "服务器错误" });
});

// 启动
app.listen(3000, () => {
  console.log("TS + Express5 人口服务运行在 http://localhost:3000");
});

四、启动运行

bash

运行

复制代码
npx ts-node src/index.ts

五、测试接口

plaintext

复制代码
http://localhost:3000/search/北京
http://localhost:3000/search/上海

返回:

json

复制代码
{
  "city": "北京",
  "population": 2154,
  "year": 2024,
  "unit": "万人"
}
相关推荐
草莓熊Lotso1 小时前
【Linux网络】深入理解 HTTP 协议(二):从协议格式到手写工业级 HTTP 服务器
linux·运维·服务器·网络·c++·http
上海云盾第一敬业销售2 小时前
服务器遭受攻击的应对策略及快速防护实践
运维·服务器·web安全·ddos
yyuuuzz8 小时前
独立站的技术基础与常见运维问题
大数据·运维·服务器·网络·数据库·aws
海兰8 小时前
【文字三国志:第一篇】天命重构,大语言模型(LLM)动态生成文言风格的叙事文本的文字游戏
人工智能·游戏·语言模型
日取其半万世不竭12 小时前
iftop、nethogs 和 nload:Linux 服务器网络流量实时监控工具介绍
linux·运维·服务器
mounter62512 小时前
Linux 内核资源管理:控制组(cgroup)的演进与“策略组”新提案
linux·运维·服务器·cgroup·kernel
bksczm12 小时前
文件在磁盘中的存储方式
linux·运维·服务器
L16247612 小时前
OpenSSH 半自动升级方案(独立编译 + 手动迁移 + 重建 systemd 服务)
linux·服务器·ssh
Wpa.wk12 小时前
win环境本地文件上传远程服务器(scp/远程连接工具)
运维·服务器