const fs = require('fs'); const path = require('path'); export class NodeId { private _nodeId: Promise | null = null; public get nodeId() { if (this._nodeId) { return this._nodeId } else { return this.getNodeId(); } } async getNodeId() { let file = path.join(__dirname, 'nodeId.txt'); try { fs.accessSync(file, fs.constants.F_OK) // File exists this._nodeId = fs.readFileSync(file, 'utf8'); //console.log("Read: " + this.nodeId); } catch (err) { // File does not exist this._nodeId = Promise.resolve(this.uuidv4()); fs.writeFileSync(file, await this._nodeId); //console.log("Generating nodeId: " + this.nodeId); } return this._nodeId; } uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } }