Is concurrent access to shared array a problem in Node.js


How is node handling events? One at the time, or concurrent?

I need to know, if there is going to be concurrent access to a shared array, like in the following example:

var ws          = require("./ws.js"),
connections = [];

ws.createServer(function( socket ){

// add to connection array
socket.on('connect', function(){

// remove from connection array
socket.on('close', function(){
var i = connections.indexOf(socket);


When a client connects, its socket is pushed to the array. When the connection is closed, i want to remove it from the connections array.

But, in other languages this could lead to concurrency issues.

Fx. If two connections is closed at the same time:

  • Connection A finds its socket in index 4
  • Connection B finds its socket in index 5
  • Connection A deletes itself from index 4
  • Connection B deletes itself from index 5 (but it is now index 4)

Will this ever be a problem, or can i assume that only one callback is handled at a time?

Problem courtesy of: Michael Andersen


No, this will not be a problem, because your node.js code is executed in a single thread. You will not have the same function called simultaneously.

Solution courtesy of: Caolan

View additional discussion.

Show your support

Clapping shows how much you appreciated Jamie Munro’s story.