Search code examples
javascriptnode.jsdenoopine

How would I get the listener port from Opine as I would in Express?


I'm trying to use this code I normally used in express, but in Opine with Deno and it doesn't work, is there any way that I can get the port from the listener function on Opine?

let listener = app.listen(randomPort, function(){
    console.log('Listening on port ' + listener.address().port);
});

Solution

  • EDIT: Updating to cast listener type as a Deno native type, as it's more accurate.


    Currently, the interfaces defined in the module won't show this, but after a bit of console logging, I see that when running your code:

    let listener = app.listen(randomPort, function(){
        console.log('Listening on port ' + listener.address().port);
    });
    

    the value of listener.listener.addr is an object like this:

    { hostname: "0.0.0.0", port: 8000, transport: "tcp" }
    

    Unfortunately, since this is not explicitly declared in the type, you'll get a linting error if you're using TypeScript. We can hack around this with a bit of type coercion:

    // Update: using the correct Deno native type
    const listenerAddr = listener.listener.addr as Deno.NetAddr;
    const currentPort = listenerAddr.port
    
    // Original: using hack-ish type casting
    const currentPort: number = (listener.listener.addr as { port: number }).port