确保只运行nodejs应用程序的单个实例

Ron*_*gar 10 mutex single-instance node.js

这是一种优雅的方法来确保只运行一个nodejs应用程序实例吗?我尝试使用pidlock npm,但是,它似乎只适用于*nix系统.是否可以使用互斥锁?谢谢

juz*_*aai 10

我刚刚找到了single-instance适用于所有平台的库。我可以确认它在 Windows 上运行良好。

您可以通过以下方式安装它,npm i single-instance并且需要像这样包装您的应用程序代码:

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'
});
Run Code Online (Sandbox Code Playgroud)

如果我正确理解它的源代码,它使用套接字实现锁定:如果它可以连接到套接字,则应用程序已经在运行。如果无法连接,则会创建套接字。