From 1ffe2b985e0001467781734558d4819c038eab21 Mon Sep 17 00:00:00 2001 From: leeching Date: Tue, 3 Jul 2018 10:07:25 +0800 Subject: [PATCH] feat: add destroy method for backward compatibility --- binding/nodejs/ip2region.js | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/binding/nodejs/ip2region.js b/binding/nodejs/ip2region.js index c6396cb..829b227 100644 --- a/binding/nodejs/ip2region.js +++ b/binding/nodejs/ip2region.js @@ -55,7 +55,23 @@ function getLong(buffer, offset) { class IP2Region { static create(dbPath) { - return new IP2Region({dbPath}); + const oldInstance = IP2Region._instances.get(dbPath); + if (oldInstance) { + return oldInstance; + } else { + const instance = new IP2Region({ dbPath }); + IP2Region._instances.set(dbPath, instance); + return instance; + } + } + + /** + * For backward compatibility + */ + static destroy() { + IP2Region._instances.forEach(([key, instance]) => { + instance.destroy(); + }); } constructor(options = {}) { @@ -72,6 +88,8 @@ class IP2Region { ); } + IP2Region._instances.set((this.dbPath = dbPath), this); + this.totalBlocks = this.firstIndexPtr = this.lastIndexPtr = 0; this.calcTotalBlocks(); @@ -87,6 +105,7 @@ class IP2Region { */ destroy() { fs.closeSync(ip2rObj.dbFd); + IP2Region._instances.delete(this.dbPath); } /** @@ -279,4 +298,6 @@ class IP2Region { } } +IP2Region._instances = new Map(); + module.exports = IP2Region;