Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensuring that only a single instance of a nodejs application is running

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

like image 208
Ron Yadgar Avatar asked Nov 01 '15 08:11

Ron Yadgar


People also ask

How do I run a node js app as a background service?

Run command systemctl start node-app-service-name to start the service, the node-app-service-name is the service file name as above. If you want to run node in background every time when the Linux OS startup, you can run the command systemctl enable node-app-service-name in a terminal to achieve this.

How do I keep node running app?

js application locally after closing the terminal or Application, to run the nodeJS application permanently. We use NPM modules such as forever or PM2 to ensure that a given script runs continuously. NPM is a Default Package manager for Node.

What is an instance in node?

A Bigtable instance is a container for your data. Instances have one or more clusters, located in different zones. Each cluster has at least 1 node. A table belongs to an instance, not to a cluster or node. If you have an instance with more than one cluster, you are using replication.

Is NodeJS real time data intensive?

Node. js uses non-blocking, event driven I/O to offer efficiency and remain lightweight in terms of in-memory usage to data intensive real time web applications that run in various distributed environments or devices.


1 Answers

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.

like image 171
juzraai Avatar answered Oct 05 '22 21:10

juzraai