node js - 检测并防止重复进程

时间:2018-05-29 16:01:04

标签: javascript node.js

在我只希望一次运行一个应用程序实例的情况下,我如何检测并阻止代码库运行两次?

目前,我的代码是从命令行启动的,我打算在应用程序运行并发出命令时,将消息发送到预先存在的实例

1 个答案:

答案 0 :(得分:1)

正如评论中所提到的,阻止创建同一进程的一种方法是创建lock文件。此文件通常不包含任何内容,但您可以在其中放置任何内容。我们只需要知道该文件是否存在。

const fs = require('fs')
const path = require('path')

// Create the path to the lock file
const lockFile = path.join(__dirname, './lock')
// Test the lock file
const lock = fs.statSync(lockFile)

if (lock.isFile()) {
  // The file already exists, exit the process
  process.exit()
} else {
  // The file does not exist, let's create it
  fs.writeFileSync(lockFile, '')

  // Before the application quits, remove the lock file
  process.on('beforeExit', () => fs.unlinkSync(lockFile))
}

锁定文件的缺点是,如果您的应用程序崩溃,lock文件将不会被删除,并且需要手动删除。

注意: process.on()需要位于else,否则退出的应用程序可能会删除该文件。

相关问题