Created
October 14, 2025 07:24
-
-
Save Kjue/7488e9508c782dfae73dd5cfeaaec1a3 to your computer and use it in GitHub Desktop.
Node CLI for any server using unix socket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 foregoes the worker process. # | |
| // ## It simply opens the socket and listens for commands. # | |
| // ## Use this if you can guarantee the server is not blocked. # | |
| // ################################################################## | |
| const SOCKET_PATH = path.join(os.tmpdir(), 'node-app-daemon-single.sock'); | |
| 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); | |
| } | |
| startServerProcess(); | |
| } | |
| } else { | |
| console.error('An unexpected error occurred while probing the socket:', err); | |
| process.exit(1); | |
| } | |
| }); | |
| function startServerProcess() { | |
| console.log(`🚀 Server process with PID: ${process.pid} is starting.`); | |
| console.log(' ✅ Application logic is running in this process.'); | |
| const shutdown = () => { | |
| console.log('\n[Server] 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()); | |
| console.log(`[Server] Received command: "${command}" with args:`, args); | |
| if (command === 'stop') { | |
| client.write('✅ Server is shutting down...'); | |
| client.end(); | |
| shutdown(); | |
| return; | |
| } | |
| const response = handleCommand(command, args); | |
| client.write(response); | |
| client.end(); | |
| }); | |
| }).listen(SOCKET_PATH); | |
| process.on('SIGINT', shutdown); | |
| process.on('SIGTERM', shutdown); | |
| } | |
| function handleCommand(command, args) { | |
| let response; | |
| switch (command) { | |
| case 'status': | |
| response = JSON.stringify({ | |
| processPid: 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 = args[0]; | |
| if (!orgName) { | |
| response = "Error: Organization name is required."; | |
| } else { | |
| response = `Organization "${orgName}" created successfully.`; | |
| } | |
| break; | |
| default: | |
| response = `Error: Unknown command "${command}"`; | |
| } | |
| return response; | |
| } | |
| 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); | |
| }); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please see my blog post about this on dev.to.