node.js - 在 Node JS (Hapijs) 中如何全局访问 Server 变量

标签 node.js module hapi.js

这一定很简单,但我找不到好的解决方案。

例如,在 Node 模块中,我想记录是否出现问题。所以我需要使用 Hapi 函数 server.log(...)。一个例子:

在 server.js 中:

const server = new Hapi.Server({...});
server.connection({port:3000});
server.start((err) => {
  if (err) { throw err }
}

在文件 test.js 中,我想使用在 server.js 中创建的服务器变量。由于记录和加载其他插件,它应该可以在任何模块中使用。

class Test {
  logInfo(text) {
    server.log(['info'], text);  // this will not work.
  }
}
module.exports = new Test();

我当然可以将服务器添加到模块的每次调用中,但这有点过分了。

如何在创建的模块外部获取对服务器变量的引用?

最佳答案

如果您想在请求期间记录消息,可以使用 request.log(...)

或者,您可以使用 server.log(...)通过访问处理程序中 request 对象上的 server 对象。

{
    method: 'GET',
    path: '/do/stuff',
    handler: function (request, reply) {
        request.server.log('server.log() method');

        request.log('request.log() method');

        const test = new Test(request.server);

        test.logInfo('some text here');
    }
}

查看我的answer on logging在 hapi 也是如此。

在您的情况下,如果您特别想在 hapi 服务器事件中记录消息,则需要将对服务器对象的引用传递给您的模块。

class Test {
    private server;

    constructor(server) {
        this.server = server;
    }

    logInfo(text) {
        this.server.log(['info'], text);  // this will work.
    }
}

但是您问题的评论者可能是对的。如果您想避免模块的紧密耦合,则应该避免这种模式。

关于node.js - 在 Node JS (Hapijs) 中如何全局访问 Server 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44929751/

相关文章:

javascript - 如何 stub Hapi 处理程序?

node.js - 使用回调和 promise 对 mongodb 查询的不同响应

node.js - 来自 dokku 容器的 DNS 查找

node.js - 为什么建议不要在 Node.js 代码的任何地方关闭 MongoDB 连接?

node.js - 使用 Phantom 抓取表单提交信息

javascript - 使用 Jest 的 rewire 来监视私有(private)函数中使用的 console.log

python - 三个python模块,相互调用

python - 是否有用于访问 Advantage 数据库服务器的 Python 模块?

javascript - nodejs 的 View 引擎 Handlebar 在 Hapijs 上的 Angular 代码

node.js - 将请求 header 添加到 Node 中的 Azure Application Insights 事件