There are OS-specific ways of looking at all the processes running on the current computer so you could use that (by running an external process as a child_process) to see if your server is already running.
But, for a cross platform mechanism, you can just put a little http server (I call a probe server) into your process and then see if that server responds. If it does, then your app is already running. If not, then it's not.
So, put this into your app:
// pick some port not already in use locally const probePort = 8001; const probePath = '/probe'; const http = require('http'); const rp = require('request-promise'); // see if our probe server is already running rp({ uri: `http://localhost:${probePort}${probePath}`, resolveWithFullResponse: true }).then(res => { if (res.statusCode === 200) { console.log(`Our server already running in another process`); process.exit(1); } else { throw new Error(`statusCode ${res.statusCode}`) } }).catch(err => { // our process is not already running // start our own copy of the probeServer const server = http.createServer((req, res) => { if (req.url === probePath) { res.statusCode = 200; res.end("ok"); } else { res.statusCode = 404; res.end("err"); } }); server.listen(probePort); // make sure this server does not keep the process running server.unref(); // proceed with the rest of your process initialization here console.log("Our server not already running, so we can now start ours"); setInterval(() => { console.log("still running"); }, 1000); });
Note: If you already have an http server in your app, then you can just create a special probePath route in that server that responds with a 200 status and test that rather than creating another http server.
npmor Google? I immediately found a variety of packages that do this in various ways: find-process being the first resultps.