node js mysql2数据库 toml配置文件使用示例

node js 环境版本

  • NodeJS 16 or later

  • TypeScript 4.9.3 or later

依赖模块安装

bash 复制代码
npm install mysql2 --save
npm install toml --save
npm install moment-timezone --save
npm install @types/moment --save

toml配置文件解析

config.ts

javascript 复制代码
// config.ts
import fs from 'fs';
import toml from 'toml';
​
// 读取当前文件夹下的 config.toml 配置文件
let config = toml.parse(fs.readFileSync('config.toml').toString());
​
export default config;

mysql数据库链接获取

javascript 复制代码
// mysql/connection.ts
import config from "../config";
​
import mysql from 'mysql2/promise';
​
let connection: mysql.Connection;
​
const getConnection = async () => {
    if (!connection) {
        connection = await mysql.createConnection({
            host     : config.mysql.host,
            user     : config.mysql.user,
            password : config.mysql.password,
            database : config.mysql.database
        });
    }
​
    return connection;
}
​
export {
    getConnection
};

mysql数据库操作对象定义

javascript 复制代码
// metrics/add-client-log.ts
import moment from "moment-timezone";
import config from "config";
import { getConnection } from "../mysql/connection";
​
export default async function addClientLog(clientId: string, eventKey: string, eventValue: string): Promise<void> {
    const connection = await getConnection();
    const enableLogging = config.runtime.enableLogging ?? false;
​
    if (!enableLogging) {
        return;
    }
​
    const date = moment().tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
    await connection.query(
        `INSERT INTO client_log
         VALUES (
             0,
             "${connection.escape(clientId)}",
             "${connection.escape(eventKey)}",
             "${connection.escape(eventValue)}",
             "${date}"
        )
    `);
}
​
复制代码

mysql数据库操作对象 使用示例

javascript 复制代码
// config.ts
import addClientLog from '../metrics/add-client-log';
​
// 使用示例
await addClientLog(123, "initialized", "localhost");
复制代码
​

相关资源

  • 数据库脚本
sql 复制代码
CREATE TABLE IF NOT EXISTS `client_log` (
  `id` int NOT NULL AUTO_INCREMENT,
  `clientId` varchar(255) DEFAULT NULL,
  `eventKey` varchar(255) DEFAULT NULL,
  `eventValue` text,
  `date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
);

config.toml

XML 复制代码
environment = "local"
​
###
# Config for the web and websockets servers
# The password is for any routes you want to password protect
# By default this is only the endpoint that lists active connections for debugging purposes
###
[server]
httpPort = 8000
websocketPort = 8080
domain = 'localhost'
password = 'changeme'
​
# A list of banned IPs
bannedIps = [
    '999.999.999.999',
]
​
# A list of banned Client IDs
bannedClientIds = [
    'df3453rewr349543utff'
]
​
# A list of banned hostnames
bannedHostnames = [
    'evil.com'
]
​
###
# MySQL is used for Logging wnen it is enabled
###
[mysql]
host = 'localhost'
user = 'root'
password = 'changeme'
database = 'test'
​
###
# Enable or disable debug output and logging
###
[runtime]
debug = true
enableLogging = false
相关推荐
山楂树の8 分钟前
Java 泛型:泛型类、泛型方法、泛型接口与通配符
java·开发语言·笔记
李兆龙的博客14 分钟前
从一到无穷大 #115:企业级 SSD 涨价后的容量利用率与磨损管理
数据库·ssd·nvme
利威尔xu16 分钟前
2026-11-18-Go接口幂等设计实战
开发语言·后端·golang
Highcharts.js27 分钟前
Highcharts与TypeScript集成指南
前端·javascript·typescript·前端框架·数据可视化·highcharts
eggwyw2 小时前
linux下的C\C++多进程多线程编程实例详解
开发语言·c++
桃李无言下自成蹊2 小时前
为什么越清晰的二维码越扫不出来:jsQR 四轮解码与 8 个真实坑
javascript
布莱克6052 小时前
Swift 枚举详解:从基础语法到关联值与模式匹配
开发语言·ios·swift·枚举
小y的笔记2 小时前
Vue 3 异步搜索实战:watch、请求取消与竞态控制
前端·javascript
布莱克6052 小时前
Swift 闭包详解:从语法到实战的完整指南
服务器·开发语言·ios·ssh·swift·闭包
小七在进步3 小时前
string的实现(3)
开发语言·c++·笔记·visual studio