NodeJS:我的节点文件与其他文件中的变量有依赖关系 [英] NodeJS: My node files have dependencies on variables in an other file

查看:704
本文介绍了NodeJS:我的节点文件与其他文件中的变量有依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用nodejs创建一个应用程序。在应用程序中,我有一个 app.js 脚本,它是将应用程序,expressjs应用程序和我使用的http服务器初始化的入口点。



只是为了澄清:这里的模块不是npm模块,它们是我自己的文件。我已经在模块中编写了该应用程序。它们只是由 require()使用的单独的脚本文件。



此应用程序有几个模块,主模块处理程序初始化。它读取包含我自己的模块的文件夹的内容,然后按照惯例在运行 require()之后调用每个模块上的 .initialize 调用不带 .js 扩展名的文件名。



但是,我有1需要应用程序变量的模块来创建一个端点,1个模块需要 httpServer 变量来创建一个Web套接字。这两个都是在 app.js 中实例化的。



看到我不知道什么样的模块会在文件夹中,如果只需要它们,我不希望向每个模块发送 app httpServer 每个1个模块。某些东西像依赖注入会很好,但是这可能没有太多的开销?



现在我刚刚添加应用程序 httpServer GLOBAL 对象。

解决方案

我通常做的是 app.js export app 我的应用程序中的其他地方可以直接要求它,而不必在任何地方处理它。我也稍微修改app.js,这样它不会听,如果它被要求作为一个模块,稍后如果我决定用另一个应用程序包装,我可以与最小的变化。这对你的问题并不重要,我只是发现它给我更多的控制单位测试。所有你真正需要的代码是 module.exports = app

 'use strict'; 
var express = require('express'),
app = express(),
config = require('config'),
pkg = require(' JSON');

//信任反向代理
app.enable('trust proxy');

app.set('version',pkg.version);
module.exports = app; //< --- *** important ***

if(app.get('env')!=='production'){
app.set('debug ',真的);
}

//调用app.boot引导应用程序
app.boot = function(skipStart){// skipStart var可以轻松进行单元测试,而无需实际启动服务器
//添加中间件
require('./中间件/');

//设置模型
app.set('models',require('./ models'));

//设置路由
require('./ routes /');

//等待dbconnection开始收听
app.on('dbopen',function(){

//设置主机参数
if(!skipStart){
let server = app.listen(config.port,function(){
app.emit('started');
console.log('Web Server listening at:http://%s:%s',server.address()。address,server.address()。port);

//邮件服务器拦截器为dev
if (app.get('env')!=='production'){
//配置smtp服务器为dev
让SMTPServer = require('smtp-server')。SMTPServer,
mailServer = new SMTPServer({
secure:false,
disabledCommands:['STARTTLS'],
onData:function(stream,session,callback){
stream.pipe .stdout); //打印消息到控制台
stream.on('end',callback);
},
onAuth:fu (auth,session,callback){
callback(null,{user:1,data:{}});
}
});
//启动smtp服务器
mailServer.listen(1025,'0.0.0.0');
} else {
//仅在生产开始议程工作
require('./ jobs.js');
console.log('Agenda Jobs Running。');
}
});
} else {
app.emit('booted');
}
});
};

//如果这是主模块,请运行引导。
if(require.main === module){
//将所有这一切移动到下一个勾选,以便我们可以在其他模块中安全地使用app.js。
process.nextTick(app.boot);
}


I am creating an app with nodejs. In the app, I have a app.js script that is the entrypoint that initializes both the app, as an expressjs app, and the http server that I use.

Just to clarify: modules here are not npm modules, they are my own files. I've written the app in modules. They are just seperate script files used by require()-ing them.

This app has several modules that a main module handler initializes. It reads the contents of a folder, which contains my own modules, and then by convention call the .initialize on each module after running a require() call on the filenames without the .js extension.

However, I have 1 module that needs the app variable to create an endpoint, and 1 module that needs the httpServer variable to create a web socket. Both of these are instansiated in app.js.

Seeing as I don't know what kind of modules will be in the folder, I don't really want to send app and httpServer to every module if they are just needed by 1 module each. Something like dependency injection would fit nice, but is that possible without to much overhead?

Right now I just temporarily added app and httpServer to the GLOBAL object.

解决方案

What I usually do is have app.js export app so that modules elsewhere in my app can require it directly rather than having to deal with passing it around everywhere. I also slightly modify app.js so that it won't "listen" if it is required as a module that way later on if i decide to wrap it with another app, I can with minimal changes. This is not important to your question, I just find it give me more control when unit testing. All you really need from the code below is module.exports = app

'use strict';
var express = require('express'),
  app = express(),
  config = require('config'),
  pkg = require('./package.json');

// trust reverse proxies
app.enable('trust proxy');

app.set('version', pkg.version);
module.exports = app; // <--- *** important ***

if (app.get('env') !== 'production') {
  app.set('debug', true);
}

// calling app.boot bootstraps the app
app.boot = function (skipStart) { // skipStart var makes it easy to unit test without actually starting the server
  // add middleware
  require('./middleware/');

  // setup models
  app.set('models', require('./models'));

  // setup routes
  require('./routes/');

  // wait for a dbconnection to start listening
  app.on('dbopen', function () {

    // setup hosting params
    if (!skipStart) {
      let server = app.listen(config.port, function () {
        app.emit('started');
        console.log('Web Server listening at: http://%s:%s', server.address().address, server.address().port);

        // mail server interceptor for dev
        if (app.get('env') !== 'production') { 
          // Config smtp server for dev
          let SMTPServer = require('smtp-server').SMTPServer,
            mailServer = new SMTPServer({
              secure: false,
              disabledCommands: ['STARTTLS'],
              onData: function(stream, session, callback){
                stream.pipe(process.stdout); // print message to console
                stream.on('end', callback);
              },
              onAuth: function (auth, session, callback) {
                callback(null, {user: 1, data: {}});
              }
            });
          // Start smtp server
          mailServer.listen(1025, '0.0.0.0');
        } else {
          // start agenda jobs only on production
          require('./jobs.js');
          console.log('Agenda Jobs Running.');
        }
      });
    } else {
      app.emit('booted');
    }
  });
};

// If this is the main module, run boot.
if (require.main === module) {
  // move all of this to next tick so we can require app.js in other modules safely.
  process.nextTick(app.boot);
}

这篇关于NodeJS:我的节点文件与其他文件中的变量有依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆