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
Ensuring that only a single instance of a nodejs application is running
Asked Answered
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. –
Brasilin
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.
© 2022 - 2024 — McMap. All rights reserved.