简体   繁体   中英

Use an entire array across multiple files Node.js

Ok so here's my problem. I got an array in my "main file" and I need to be able to use that array across other files.

var myArray = []

This array holds sockets connecting to my server, so it's constantly changing

function putsSocketsInArray () {
myArray.push(rawSockets) }

Now I wanna use that array for example, in another script to write to all the sockets in the array.

  'use strict'
//broadcast function

function talkAll (myArray, message, sender) {
    myArray.forEach(function (connection) {
        //don't want to send it to sender
        if (connection === sender) return;
    connection.write(`${message} \n`);
    });

}

module.exports = talkAll

This works as long as the function talkAll is same "main.js" file.

(code in main.js) (It's a telnet server)

telnetSocket.on('data', function (data) {

talkAll(myArray, telnetSocket.name + ">" + data, telnetSocket);
});

Well I need to seperate it out into a module, but when I do my second.js file can't use the myArray at all. It will error out that the array is not defined. Yet when I make any attempt to define it in the second.js or even try to build a function to fetch that array. the Array becomes blank.

The answer provided by jcaron below worked for me. Also kids, make sure you're not editing the wrong script for 10 minutes.

If myArray is defined in your main file, which require s another file, you need to pass your array to functions inside your second file.

var myArray = [];

var myModule = require('mymodule');
...
myModule.talkAll(myArray,message,sender);

Of course, you need to add that argument to your talkAll function.

There are lots of alternatives depending on how exactly you implemented your module. You could also have a function to set a local variable to that array.

An alternative to passing the array from main.js to individual modules is to make the array itself a module that gets required by any module that needs it.

The thing that makes this work is to realise that node modules are not merely cached but are actually proper singletons . That means that each time a module gets imported the same object gets imported.

The implementation is simplicity itself:

In shared-array.js :

var sharedArray = [];
module.exports = sharedArray;

In any file that create sockets:

var sharedArray = require('./path/to/shared-array');
// ...
sharedArray.push(socketObject);

In any file that need to use those sockets:

var sharedArray = require('./path/to/shared-array');
// ...
var socket = sharedArray[socketIndex];

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