How in nodejs to implement a ban to re-run the script, if the script is running at the moment?

You can use the file mutex

https://www.npmjs.com/package/lockfile

var lockFile = require('lockfile') try{ lockFile.lockSync('some-file.lock'); }catch(er){ if(er!=undefined){ process.exit(); } } //single run code below 

But there is a problem, if the node process is closed through the task manager, then the lock file will not be deleted => the script will never be able to work again.

Are there any other options besides writing my own module?

  • The simplest thing is to cut off the script and add a counter. - dasauser
  • @dasauser what should I chop off and what counter to add? - Kopkan
  • you can make the handler delete the file on beforeExit - nörbörnĂ«n
  • @nörbörnĂ«n The "beforeExit" event is not a condition for expressing termination, such as the calling process. - Kopkan
  • well then the handler on SIGHUP - nörbörnĂ«n

1 answer 1

Using the ffi module, you can call functions from dll

https://www.npmjs.com/package/node-ffi

But this module overlaps GetLastError codes, so I had to use WaitForSingleObject to confirm the capture of the mutex

 function tryGetMutex(mutexName, isGlobal=true){ if (isGlobal) { mutexName = "Global\\" + mutexName; } var ffi = require('ffi'); var kernel = ffi.Library('Kernel32.dll', { 'CreateMutexA': [ 'int', ['int', 'int', 'string'] ], 'WaitForSingleObject': [ 'int', ['int','int'] ] }); var mutex = kernel.CreateMutexA(0, 0, "Global\\" + mutexName); var wait = kernel.WaitForSingleObject(mutex, 1000); return( wait==0 || wait==128 );//WAIT_ABANDONED || WAIT_OBJECT_0 } if(tryGetMutex("mymutex")) { console.log("I single run code"); setInterval(function(){}, 1000); } else{ console.log("mutex lock in another application"); process.exit(); }