i creating app nodejs. in app, have app.js script entrypoint initializes both app, expressjs app, , http server use.
just clarify: modules here not npm modules, own files. i've written app in modules. seperate script files used require()-ing them.
this app has several modules main module handler initializes. reads contents of folder, contains own modules, , convention call .initialize on each module after running require() call on filenames without .js extension.
however, have 1 module needs app variable create endpoint, , 1 module needs httpserver variable create web socket. both of these instansiated in app.js.
seeing don't know kind of modules in folder, don't want send app , httpserver every module if needed 1 module each. dependency injection fit nice, possible without overhead?
right temporarily added app , httpserver global object.
what have app.js export app modules elsewhere in app can require directly rather having deal passing around everywhere. modify app.js won't "listen" if required module way later on if decide wrap app, can minimal changes. not important question, find give me more control when unit testing. need code below 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 app app.boot = function (skipstart) { // skipstart var makes easy unit test without starting server // add middleware require('./middleware/'); // setup models app.set('models', require('./models')); // setup routes require('./routes/'); // wait dbconnection 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 dev if (app.get('env') !== 'production') { // config smtp server 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 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 on production require('./jobs.js'); console.log('agenda jobs running.'); } }); } else { app.emit('booted'); } }); }; // if main module, run boot. if (require.main === module) { // move of next tick can require app.js in other modules safely. process.nexttick(app.boot); }
Comments
Post a Comment