简体   繁体   中英

How can you prevent multiple instances of imported modules using node.js?

I have three files and I am attempting to share a variable I have called sharedArray, stored in the array.js file, on my main js file and another file fileA using export. Although, it appears that main.js and fileA.js create their own instances of array.js. Is there any way to prevent this and have both main.js and fileA.js point to the same variable sharedArray?

main.js

const electron = require('electron');
const path = require('path');
const arrayJS = require(path.join(__dirname,"array.js"));
const {ipcMain} = electron;

function countArray(){
    console.log(`There are ${arrayJS.sharedArray.length} values in shared array`);
}

ipcMain.on('countArrayFromMain', function(e){
    countArray();
});

array.js

var sharedArray = [];

function getSharedArray(){
  return sharedArray;
}

function setSharedArray(newArray){
  sharedArray = newArray;
}

module.exports = {
  getSharedArray,
  setSharedArray
  }

fileA.js

const electron = require('electron') ;
const {ipcRenderer} = electron;
const arrayJS = require(path.join(__dirname,"array.js"));

var newArray = [1,2,3];
arrayJS.setSharedArray(newArray);

console.log(`There are ${arrayJS.sharedArray.length} values in shared array`); // outputs 3
ipcRenderer.send('countArrayFromMain'); // outputs 0

Per code, main.js represents Main process of Electron and filaA.js is for Renderer process. Since those 2 are different process, there is no way to share same object reference across processes: you should use IPC to ask one process's value if you want to achieve singleton across process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM