1

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);
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
pisanvs
  • 67
  • 1
  • 5
  • What exactly "*doesn't work*"? – Bergi Jan 26 '21 at 03:01
  • @Bergi listener.address() doesn't exist, I'm looking for an alternative – pisanvs Jan 26 '21 at 03:15
  • 1
    As far as I see it, you have to specify the port when calling `app.listen(SOMEPORT)` also in opine. So you already know the port. And if the docs don't provide a way to get the information, there probably isn't one ... – derpirscher Jan 26 '21 at 08:50

1 Answers1

2

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
Brandon
  • 122
  • 7
  • 1
    Currently the returned server just uses the generic Deno.Listener interface https://doc.deno.land/builtin/stable#Deno.Listener with the `addr` property set to `Deno.Addr`. So as a subtlety, casting to `Deno.NetAddr` https://doc.deno.land/builtin/stable#Deno.NetAddr over `{ port: number }` is slightly more aligned with the internals, though for this use-case, the end result is equivalent. – C.. Feb 24 '21 at 09:35