← back to Pm2 Migration
append-ecosystem.js
60 lines
#!/usr/bin/env node
// Append a single PM2 app entry to ecosystem.config.cjs.
// Usage: append-ecosystem.js <name> <cwd> <script>
const fs = require("fs");
const path = require("path");
const [name, cwd, script] = process.argv.slice(2);
if (!name || !cwd || !script) {
console.error("usage: append-ecosystem.js <name> <cwd> <script>");
process.exit(1);
}
const file = path.join(__dirname, "ecosystem.config.cjs");
let apps = [];
if (fs.existsSync(file)) {
try {
const cfg = require(file);
apps = cfg.apps || [];
} catch (e) {
console.error("Could not require existing ecosystem; starting fresh:", e.message);
}
}
// After rsync, the script lives at cwd root with the same basename.
const localScript = path.basename(script);
const isPython = /\.py$/i.test(localScript);
const SHIM = path.join(__dirname, "root-shim.js");
const existing = apps.findIndex((a) => a.name === name);
const entry = {
name,
cwd,
script: localScript,
...(isPython
? { interpreter: "python3" }
: { node_args: `--require ${SHIM}` }), // monkey-patches /root/* → ~/kamatera-mirror/*
autorestart: true,
watch: false,
max_memory_restart: "500M",
env: {
NODE_ENV: "production",
LOCAL_MIGRATION: "1",
KAMATERA_MIRROR: path.join(require("os").homedir(), "kamatera-mirror"),
},
};
if (existing >= 0) {
apps[existing] = entry;
console.log(`updated ${name} in ecosystem.config.cjs`);
} else {
apps.push(entry);
console.log(`appended ${name} to ecosystem.config.cjs`);
}
const out = `module.exports = {\n apps: ${JSON.stringify(apps, null, 2).replace(/\n/g, "\n ")},\n};\n`;
fs.writeFileSync(file, out);