1

I have an array declared in server.js in a Node.js application. I want the client side to be able to access the array and it's content. Is that possible? If yes, how can I do that? I tried the following but the console always says global array not defined

server.js

//connection code above this
var global_array=[];
socket.on('change', function(data){
        socket.broadcast.emit('change', data);
        global_array.push(data);
        console.log(global_array);
    });
.... //rest code

main.js

if (typeof global_array !== 'undefined' && global_array.length > 0) {
console.log(global_array);
}  else {
console.log("global array not defined");
}
2
  • 3
    In whatever it is that outputs the HTML, just output the array inside a script tag ? Commented Jun 15, 2016 at 18:29
  • @adeneo That is index.html and when I do console.log(global_array); it gives ReferenceError:global_array is not defined Commented Jun 15, 2016 at 18:41

1 Answer 1

3

Defining a variable on your server doesn't mean that it will be also accessible on the client-side.

I suggest initializing the global_array variable on the client-side, too. When the client connects to the server, the server will send the initial array data or an empty array (if there is no data). Then, the client will be listening for the change event.

Server-side code:

var global_array = [];

io.on('connection', function(socket) {
  socket.emit('initialize array', global_array);
  socket
    .on('change', function(data) {
      socket.broadcast.emit('change', data);
      global_array.push(data);
      console.log(global_array);
    });
});

Client-side code:

var global_array;

socket
  .on('initialize array', function(initial_global_array) {
    global_array = initial_global_array;
  })
  .on('change', function(data) {
    global_array.push(data);
  });

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.