Jarosław Rewers Jarosław Rewers - 4 months ago 8
Node.js Question

Use app var in file required by app in Node

I have following structure:

- build/
-- app.js
-- middlware/
--- authorization.js
-- model
--- Model1.js
--- Model2.js
-- routes
--- common.js


It's just beginning, and there will be more files. I just created an auth mechanism using passport and its working, but now I want to move it outside
app.js
file to
middleware/authorization.js
, and move my 'login' route to routes. When I do that I receive error

app.use(passport.initialize());
^



ReferenceError: app is not defined


How can I refer to app in file, which is required in app?

My other question is that I intend to use mongoose models which are now also defined in
app.js
but will be placed in
model/*js
. Should I explicitly require necessary modules in each files, for example mongoose in
model/*.js
, then mongoose and model files in
middleware/authorization.js
or is there any magical way to just use all variables throughout whole app (not counting global variables)?

And my last question is, how can I import to
app.js
all other js files from
build/
and its subdirectories? Maybe I should just do that manually, every file in separate require?

Answer

You need to inject app into your authorization module. ex.

authorization.js

module.exports = function(app) {
    app.use(passport.initialize());
}

app.js

var authorization = require('./middleware/authorization')(app);
Comments