Ensuring that only a single instance of a nodejs application is running
Asked Answered
L

1

18

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

Lynettelynn answered 1/11, 2015 at 8:10 Comment(1)
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
K
11

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.

Kalil answered 15/12, 2018 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.