简体   繁体   English

如何导出中心变量参考

[英]How to export reference of central variable

I'm using Hapi. 我正在使用Hapi。

I'm also using NES client to connect to another node instance. 我还使用NES客户端连接到另一个节点实例。 In order to access this socket from the routes, I attach it to the server variable like so: 为了从路由访问此套接字,我将其附加到服务器变量,如下所示:

exports = async () => {
  //api
  var server = new Hapi.Server({
    host: process.env.WEB_HOST || '127.0.0.1',
    port: process.env.WEB_PORT || '8080'
  });

  // register plugins
  await server.register(plugins);

  // add routes
  await routes(server);

  server.socket = new Socket(identifier); // uses NES

  return server;
}

I want to access the socket from a library file. 我想从库文件访问套接字。 How do I do this without having to pass it the server variable each time? 如何做到这一点而不必每次都将服务器变量传递给它? When I try to module.exports the server, it never gives me a reference, only a version of the variable at the time it was exported. 当我尝试对服务器进行module.exports ,它从不提供引用,只是在导出变量时提供了一个版本。

Have you tried server.decorate. 您是否尝试过server.decorate。 If I understood correctly , you want to access your socket variable from routes. 如果我理解正确 ,则想从路由访问套接字变量。 Why not just create basic plugin and create your socket instance and pass that into server object. 为什么不创建基本插件并创建您的套接字实例,然后将其传递到服务器对象呢? For example; 例如;

exports.plugin = {
    async register(server, options) {                 
        server.decorate('server', 'socketConn', new Socket(identifier));
    },
    name: 'socket-connection'
};

and in your routes you can access this variable as request.server.socketConn . 并且在您的路由中,您可以以request.server.socketConn访问此变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM