[英]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.我有三个文件,我正在尝试共享一个我称为 sharedArray 的变量,该变量存储在 array.js 文件中,在我的主 js 文件和另一个使用 export 的文件 fileA 上。 Although, it appears that main.js and fileA.js create their own instances of array.js.虽然,main.js 和 fileA.js 似乎创建了自己的 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 和 fileA.js 都指向同一个变量 sharedArray?
main.js 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数组.js
var sharedArray = [];
function getSharedArray(){
return sharedArray;
}
function setSharedArray(newArray){
sharedArray = newArray;
}
module.exports = {
getSharedArray,
setSharedArray
}
fileA.js文件A.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.每个代码,main.js 代表filaA.js
的主进程, main.js
代表 Renderer 进程。 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.由于这两个是不同的进程,因此无法跨进程共享相同的 object 引用:如果要跨进程实现 singleton,则应使用 IPC 询问一个进程的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.