I want access my own variable, app.locals.port, from app.js, inside my routes/index.js file.
app.js:
app.locals.port = 3001;
var index = require('./routes/index');
app.use('*', index); // use router in ./routers/index.js
routes/index.js:
var app = require('../app');
console.log('app.locals.port: ' + app.locals.port);
Output in my log when running npm start --> nodemon -e css,ejs,js,json,html,pug ./bin/www:
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
app.locals.port: undefined
My current workaround is to use a global:
app.js
global.port = 3001;
routes/index.js
console.log('global.port: ' + global.port);
Thank you.
You need to pass the app object through to routes/index.js.
So in your app.js file you could have something like:
const express = require('express')
const app = express()
app.locals.port = 3001
const index = require('./routes/index')(app)
app.use('*', index)
app.listen(app.locals.port, function() {
console.log('Server listening on ' + app.locals.port)
})
and then in routes/index.js:
const express = require('express')
module.exports = function(app) {
const router = express.Router()
router.get('/', function(req, res) {
console.log(app.locals.port)
res.send('Hello from index.js!')
})
return router
}
The app variable in routes/index.js will then be available within the scope of the module.exports function, which can then be passed to other functions within the file.
As you've also mentioned in the comments, the app object is attached to each request, so if you only need access to the app object within the scope of a route, you simplify your code.
app.js
const express = require('express')
const app = express()
app.locals.port = 3001
const index = require('./routes/index')
app.use('*', index)
app.listen(app.locals.port, function() {
console.log('Server listening on ' + app.locals.port)
})
routes/index.js
const express = require('express')
const router = express.Router()
router.get('/', function(req, res) {
console.log(req.app.locals.port)
res.send('Hello from index.js!')
})
module.exports = router