Skip to content

Instantly share code, notes, and snippets.

@Kjue
Last active October 14, 2025 08:51
Show Gist options
  • Select an option

  • Save Kjue/45f7e86d0a547cab3a4e4a740da62aa2 to your computer and use it in GitHub Desktop.

Select an option

Save Kjue/45f7e86d0a547cab3a4e4a740da62aa2 to your computer and use it in GitHub Desktop.
Node CLI for any server using unix socket and non-blocking worker.
const cluster = require('node:cluster');
const net = require('node:net');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
// ##################################################################
// ## Sample script that showcases a supposed server application #
// ## with integrated CLI. This sample establishes master with #
// ## worker process to address blocking concerns. #
// ##################################################################
const SOCKET_PATH = path.join(os.tmpdir(), 'node-app-daemon.sock');
if (cluster.isPrimary) {
const [,, command, ...args] = process.argv;
const probeClient = net.createConnection(SOCKET_PATH);
probeClient.on('connect', () => {
probeClient.end();
if (command) {
runCommand(command, args);
} else {
console.log('ℹ️ Server is already running.');
showHelpAndExit();
}
});
probeClient.on('error', (err) => {
if (err.code === 'ECONNREFUSED' || err.code === 'ENOENT') {
if (command) {
console.error('❌ Error: Server is not running. Cannot execute command.');
showHelpAndExit();
} else {
console.log('ℹ️ No active server found. Starting a new one...');
if (fs.existsSync(SOCKET_PATH)) {
fs.unlinkSync(SOCKET_PATH);
}
startMasterProcess();
}
} else {
console.error('An unexpected error occurred while probing the socket:', err);
process.exit(1);
}
});
function startMasterProcess() {
console.log(`πŸš€ Master process with PID: ${process.pid} is starting.`);
const shutdown = () => {
console.log('\n[Master] Shutting down, removing socket...');
if (ipcServer) ipcServer.close();
if (fs.existsSync(SOCKET_PATH)) {
fs.unlinkSync(SOCKET_PATH);
}
setTimeout(() => process.exit(0), 200);
};
const ipcServer = net.createServer((client) => {
client.on('data', (data) => {
const { command, args } = JSON.parse(data.toString());
if (command === 'stop') {
client.write('βœ… Server is shutting down...');
client.end();
shutdown();
return;
}
const worker = Object.values(cluster.workers)[0];
if (worker) {
worker.send({ cmd: command, args: args });
const messageListener = (msg) => {
if (msg.response) {
client.write(msg.response);
client.end();
worker.removeListener('message', messageListener);
}
};
worker.on('message', messageListener);
} else {
client.write('Error: No worker process is running.');
client.end();
}
});
}).listen(SOCKET_PATH);
cluster.fork();
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
}
function showHelpAndExit() {
console.log('\nUsage: node app.js <command> [arguments]\n');
console.log('Available commands:');
console.log(' status Check the status of the running server');
console.log(' create:org <name> Create a new organization');
console.log(' stop Stop the running server daemon');
process.exit(0);
}
function runCommand(command, args) {
const client = net.createConnection(SOCKET_PATH);
client.on('connect', () => {
const payload = JSON.stringify({ command, args });
client.write(payload);
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('error', (err) => {
console.error('❌ Error connecting to server to run command:', err.message);
process.exit(1);
});
}
} else {
console.log(` βœ… Worker process ${process.pid} started.`);
process.on('message', (msg) => {
console.log(`[Worker] Received command: "${msg.cmd}" with args:`, msg.args);
let response;
switch (msg.cmd) {
case 'status':
response = JSON.stringify({
workerPid: process.pid,
uptime: `${Math.round(process.uptime())}s`,
memoryUsage: `${Math.round(process.memoryUsage().rss / 1024 / 1024)}MB`,
}, null, 2);
break;
case 'create:org':
const orgName = msg.args[0];
if (!orgName) {
response = "Error: Organization name is required.";
} else {
response = `Organization "${orgName}" created successfully.`;
}
break;
default:
response = `Error: Unknown command "${msg.cmd}"`;
}
process.send({ response });
});
}
@Kjue
Copy link
Author

Kjue commented Oct 14, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment