2

My understanding of node.js is that the process exits when callback queue is empty, meaning all the callbacks are executed. But, I noticed some node APIs callback will never get called in some scenarios. How would node know when to exit the process? Would none of my callbacks never get called in some scenario?

var net = require('net');
var client = net.connect({port: 8080}, function () {// first callback
  console.log('connected');
});
client.on('error', function () {// second callback
  console.log('error');
});
// end of script

I tried the example code above, the process would still exit, even it cannot make connect. But, the first callback never gets called. In this case, how would node know that the first callback may not get called, so the process would still exit instead of just hanging there?

My educated guess is that, those callbacks are event callbacks, so they are not considered normal callbacks. If node know that these callbacks may not get called, would it happened that node exit the process before neither of my callback gets called in some scenarios? (neither 'connected', nor 'error' are printed)

user926958
  • 9,355
  • 7
  • 28
  • 33

1 Answers1

2

There is a good answer at https://stackoverflow.com/a/7699579/8388.

In your example code, if you are able to connect the socket, your first callback will execute and the process will hang, unless you or the server close the socket. If, for example, you used this instead (assuming you're talking to an HTTP server on port 8080):

var client = net.connect({port: 8080}, function () {// first callback
  console.log('connected');
  client.write('GET /\n\n')
});

The server would send you some data, then close the socket. At that point, your process would exit, because it no longer had an open file descriptor.

Community
  • 1
  • 1
Joe Hildebrand
  • 10,354
  • 2
  • 38
  • 48