pid
pid

Reputation: 11607

Node.js server.listening flag always false

READ BELOW FOR ACTUAL EXPLANATION

I expect listening to return true while... well... listening. Instead, I get false despite documentation stating otherwise. Nobody made a bug report and nobody had that problem, so... it's me! Isn't it?

What's wrong with this code?

"use strict";

const mod_net = require("net");
const server = mod_net.createServer((socket) => { /* ignore */ });

console.log(`BEFORE: ${server.listening}`);

server.listen(8000, "127.0.0.1");

console.log(`AFTER: ${server.listening}`);

The output is:

> BEFORE: false
> AFTER: false

ACTUAL EXPLANATION

The codebase is rather large, I tried to reduce per SO policy to minimal code, but for fun let's look at a better example of how I messed up my own test.

What I wanted is test if a cleanup function would properly do it's work, so I threw an intentional throw between the lines and expected the cleanup function to fire.

"use strict";

const mod_net = require("net");
const server = mod_net.createServer((socket) => { /* ignore */ });

process.on("exit", () => {

  console.log(`IN EXIT: ${server.listening}`);

  if (server.listening)
  {
    server.close();

    console.log("SEND BYE-BYE MESSAGE AND 'FIN' TO SOCKETS");
  }

  console.log("GRACEFUL SHUTDOWN");
});

server.listen(8000, "127.0.0.1");

throw new Error("Boom!");

The output is:

IN EXIT: false
GRACEFUL SHUTDOWN
/home/pid/dev/test.js:26
throw new Error("Boom!");
^

As you can see, server.listener is still false. And that's the EXPECTED CORRECT behaviour of node.js because as shown in the answer by @AKX it's async. The server.listen() never had a chance to run, because the throw broke control flow before time.

What is really wrong here, is the attempt to simulate an async exception by writing it there!

Sadly for me, this attempt is not representative of the actual bug I'm encountering in the full codebase.

Upvotes: 2

Views: 243

Answers (1)

AKX
AKX

Reputation: 169051

server.listen is asynchronous. Try

server.listen(8000, "127.0.0.1", () => {
    console.log(`AFTER: ${server.listening}`); 
}) ;

Upvotes: 4

Related Questions