首页 > 解决方案 > 我如何像在 Express 中一样从 Opine 获取侦听器端口?

问题描述

我正在尝试使用我通常在 express 中使用的代码,但是在带有 Deno 的 Opine 中它不起作用,有什么方法可以从 Opine 上的侦听器函数获取端口?

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

标签: javascriptnode.jsdenoopine

解决方案


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

推荐阅读