VirtualPR/backend/scripts/dev.js

47 lines
1.1 KiB
JavaScript

import { execSync, spawn } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import dotenv from 'dotenv';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
dotenv.config({ path: path.join(root, '.env') });
const port = Number(process.env.PORT || 4000);
function pidsOnPort() {
try {
return execSync(`lsof -tiTCP:${port} -sTCP:LISTEN`, { encoding: 'utf8' })
.split(/\s+/)
.map((value) => Number(value))
.filter(Boolean);
} catch {
return [];
}
}
for (const pid of pidsOnPort()) {
try {
process.kill(pid);
console.log(`Stopped process ${pid} on port ${port}`);
} catch {
try {
execSync(`kill ${pid}`);
console.log(`Stopped process ${pid} on port ${port}`);
} catch {
console.warn(`Could not stop process ${pid} on port ${port}`);
}
}
}
await new Promise((resolve) => setTimeout(resolve, 800));
const child = spawn(process.execPath, ['--watch', 'src/index.js'], {
cwd: root,
stdio: 'inherit',
});
child.on('exit', (code, signal) => {
if (signal) process.kill(process.pid, signal);
process.exit(code ?? 0);
});