javascript - 我如何像在 Express 中一样从 Opine 获取侦听器端口?
问题描述
我正在尝试使用我通常在 express 中使用的代码,但是在带有 Deno 的 Opine 中它不起作用,有什么方法可以从 Opine 上的侦听器函数获取端口?
let listener = app.listen(randomPort, function(){
console.log('Listening on port ' + listener.address().port);
});
解决方案
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
推荐阅读
- flutter - Flutter 为什么调用 addInitialChild() 后 firstChild 没有大小
- firebase - 为什么我在 firebasestore 中获得了这么多的阅读量?颤振聊天应用
- c - 如何使用 SDL2-mixer-dev 获取 MP3 的持续时间
- css - 使子元素不受 CSS 动画的影响
- python - 用于简单基本代码的 Jenkins 声明式管道
- java - 如何让我的程序检查数组是否包含 JLabel?
- django - django 管理更改页面添加外键错误:服务器拒绝连接
- sql - 如何将 MyDate 格式化为 DD/MM/YYYY
- streaming - 如何计算 Spark 结构化流作业的输入和处理速率?
- printer-control-language - 将通过串行端口读取打印机作业状态的演示代码