Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

javascript - 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);
});
question from:https://stackoverflow.com/questions/65895110/how-would-i-get-the-listener-port-from-opine-as-i-would-in-express

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

const currentPort: number = (listener.listener.addr as { port: number }).port

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...