nodejs项目的正确打开方式,typescript + koa

这篇博客介绍了如何以typescript和koa为基础搭建一个nodejs项目。内容包括目录结构、package.json、核心模块如错误处理、数据库配置、环境变量、工具函数、常量、中间件、实体模型、组件以及应用启动类。特别提到了使用typeorm作为ORM和log4js进行日志管理,以及通过装饰器模式实现的路由配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

koa + typescript

typescript + tslint 规范化代码,选择typeorm作为数据库的orm,选择log4js输出日志

1. 目录结构

├── bin
│   └── www.ts // 启动应用
├── logs // 存放日志
├── src 
│   ├── app
│   │   ├── components // 控制器组件
│   │   │   ├── account
│   │   │   │   ├── account.controller.ts
│   │   │   │   └── account.service.ts
│   │   │   └── user
│   │   │       ├── user.controller.ts
│   │   │       └── user.service.ts
│   │   ├── constants // 常量
│   │   │   └── index.ts
│   │   ├── core // 一些核心类或全局引用的方法
│   │   │   ├── error.ts
│   │   │   └── logger.ts
│   │   ├── database // 数据库连接
│   │   │   └── index.ts
│   │   ├── entities // 实体
│   │   │   └── user
│   │   │       ├── user.entity.ts
│   │   │       └── user.model.ts
│   │   ├── middleware // 中间件
│   │   │   ├── error.middleware.ts
│   │   │   ├── jwt.middleware.ts
│   │   │   ├── logger.middleware.ts
│   │   │   └── response.middleware.ts
│   │   └── utils // 工具函数
│   │   │   └── crypto.ts
│   │	└── app.ts // 应用启动类
│   └── environments  // 多环境配置
│       ├── env.dev.ts
│       ├── env.prop.ts
│       └── index.ts
├── nodemon.json // nodemon 配置, watch ts文件
├── package-lock.json
├── package.json
├── tsconfig.json
└── tslint.json

2. package.json

{
   
  "name": "huzz-koa-template",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
   
    "@koa/cors": "^3.0.0",
    "koa": "^2.11.0",
    "koa-body": "^4.1.1",
    "koa-jwt": "^3.6.0",
    "koa-route-decors": "^1.0.3",
    "koa-router": "^7.4.0",
    "koa-static": "^5.0.0",
    "log4js": "^5.3.0",
    "mysql2": "^2.0.0",
    "reflect-metadata": "^0.1.13",
    "typeorm": "^0.2.20"
  },
  "devDependencies": {
   
    "@types/jsonwebtoken": "^8.3.5",
    "@types/koa": "^2.0.52",
    "@types/koa-router": "^7.0.42",
    "@types/koa-static": "^4.0.1",
    "@types/koa__cors": "^2.2.3",
    "cross-env": "^6.0.3",
    "nodemon": "^1.19.4",
    "ts-node": "^8.5.0",
    "tslint": "^5.20.1",
    "tslint-config-standard": "^9.0.0",
    "typescript": "^3.7.2"
  },
  "scripts": {
   
    "dev": "cross-env NODE_ENV=development nodemon --config nodemon.json",
    "compile": "tsc",
    "start": "npm run compile && pm2 start ./bin/www --name app",
    "restart": "npm run compile && pm2 start ./dist/app/app.js",
    "stop": "pm2 stop app"
  },
  "repository": {
   
    "type": "git",
    "url": "git+https://github.com/xhuz/huzz-koa-template.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
   
    "url": "https://github.com/xhuz/huzz-koa-template/issues"
  },
  "homepage": "https://github.com/xhuz/huzz-koa-template#readme"
}

3. 开始

1. core
  1. 自定义错误,
    // error.ts
    // 继承自原生Error类, 方便抛出各类异常
    export class CustomError extends Error {
          
      code: number;
      constructor(code: number, message: string) {
         
        super(message);
        this.code = code;
      }
    }
    
  2. 配置logger
    // logger.ts 具体配置自行查看log4js 文档
    import {
         configure, getLogger} from 'log4js';
    import {
         resolve} from 'path';
    import {
         Context} from 'koa';
    
    const logPath = resolve(__dirname, '../../../logs'); // log存放路径,确保该路径存在
    
    configure({
         
      appenders: {
         
        console: {
         type: 'console'},
        dateFile: {
         type: 'dateFile', filename: `${
           logPath}/log.log`, pattern: 'yyyy-MM-dd', alwaysIncludePattern: true, keepFileExt: true}
      },
      categories: {
         
        default: {
         
          appenders: ['console', 'dateFile'],
          level: 'info'
        },
        mysql: {
         
          appenders: ['console', 'dateFile'],
          level: 'info'
        }
      }
    });
    
    export const logger = getLogger('default');
    export const</
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值