Is there an elegant way to ensure that only one instance of a nodejs app is running? I tried to use pidlock npm, however, it seems that it works only on *nix systems. Is it possible by using mutex? Thanks
Asked
Active
Viewed 3,538 times
17
-
I could not find a simple cross platform way to do this from within node.js. I ended up doing this by just putting a check in my startup script on Linux using ps to check for the script name. – jfriend00 Nov 01 '15 at 09:19
1 Answers
9
I've just found single-instance
library which is intended to work on all platforms. I can confirm that it works well on Windows.
You can install it by npm i single-instance
and you need to wrap your application code like this:
const SingleInstance = require('single-instance');
const locker = new SingleInstance('my-app-name');
locker.lock().then(() => {
// Your application code goes here
}).catch(err => {
// This block will be executed if the app is already running
console.log(err); // it will print out 'An application is already running'
});
If I understand its source code correctly, it implements the lock using a socket: if it can connect to a socket, then the application is already running. If it can't connect, then it creates the socket.

juzraai
- 5,693
- 8
- 33
- 47