xiaoju-survey/server/scripts/run-local.ts
alwayrun 642f4f08eb
feat: 调整服务端环境变量导入机制 (#43)
1、为环境变量 process.env 增加 TypeScript 类型检测与感知
2、增加 dotenv & @types/node 处理支持 .env文件环境变量导入机制
2024-01-16 21:46:08 +08:00

32 lines
1019 B
TypeScript

import { MongoMemoryServer } from 'mongodb-memory-server';
import { spawn } from 'child_process';
async function startServerAndRunScript() {
// 启动 MongoDB 内存服务器
const mongod = await MongoMemoryServer.create();
const mongoUri = mongod.getUri();
console.log('MongoDB Memory Server started:', mongoUri);
// 通过 spawn 运行另一个脚本,并传递 MongoDB 连接 URL 作为环境变量
const tsnode = spawn('cross-env', [`XIAOJU_SURVEY_MONGO_URL="${mongoUri}"`, 'npx', 'ts-node-dev', './src/index.ts'], {
stdio: 'inherit',
shell: process.platform === 'win32'
});
tsnode.stdout?.on('data', (data) => {
console.log(data.toString());
});
tsnode.stderr?.on('data', (data) => {
console.error(data);
});
tsnode.on('close', (code) => {
console.log(`Nodemon process exited with code ${code}`);
mongod.stop(); // 停止 MongoDB 内存服务器
});
}
startServerAndRunScript().catch((err) => {
console.error('Error starting server and script:', err);
});