From 0ae637e11d72f71462bef8f7dfe968e25a852e93 Mon Sep 17 00:00:00 2001 From: Andrey Lushnikov Date: Mon, 19 Dec 2022 17:44:21 -0800 Subject: [PATCH] fix: do not subscribe to process signal handlers unless necessary Fixes https://github.com/moxystudio/node-proper-lockfile/issues/111 --- lib/lockfile.js | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/lib/lockfile.js b/lib/lockfile.js index 97b6637..07136be 100644 --- a/lib/lockfile.js +++ b/lib/lockfile.js @@ -248,6 +248,8 @@ function lock(file, options, callback) { lastUpdate: Date.now(), }; + ensureTeardown(); + // We must keep the lock fresh to avoid staleness updateLock(file, options); @@ -326,15 +328,24 @@ function getLocks() { return locks; } -// Remove acquired locks on exit -/* istanbul ignore next */ -onExit(() => { - for (const file in locks) { - const options = locks[file].options; +let hasTeardown = false; - try { options.fs.rmdirSync(getLockFile(file, options)); } catch (e) { /* Empty */ } - } -}); +function ensureTeardown() { + if (hasTeardown) { return; } + hasTeardown = true; + + // Remove acquired locks on exit. + // Do not setup exit listeners unless there's a need since they subscribe to + // node.js signal handlers and change default node.js behavior when handling signals. + /* istanbul ignore next */ + onExit(() => { + for (const file in locks) { + const options = locks[file].options; + + try { options.fs.rmdirSync(getLockFile(file, options)); } catch (e) { /* Empty */ } + } + }); +} module.exports.lock = lock; module.exports.unlock = unlock;