So, in my express.js 4.13.3. , in the app.js file I set an app.local var
app.set('multimedia', __dirname + '/public/multimedia');
then in the routes/settings.js I try to access that var like
var app = require('../app');
var dir = app.get('multimedia');
and I get app.get is not a function.
I also tried var dir = app.get.multimedia; and var dir = app.locals('multimedia'); and var dir = app.locals.multimedia; and still nothing.
What am I missing here?
Thanks
The problem is that you have not defined what to do when required('../app') is called. You should do this using module.exports as shown below. Try one of these approaches to fix this problem.
Approach 1:
Add this line to the app.js file.
module.exports = app;
This simply says to export the app whenever require('../app') is called. If you use require('routes/settings'); within the app.js, this line should be placed before the require('routes/settings'); or it will not work.
Approach 2:
//change the `routes/settings.js` like this
module.exports = function (app) {//notice that you pass the app to this
//............
var dir = app.get('multimedia');
console.log(dir);
//............
}
Add this line to app.js
require('routes/settings')(app);
Now you should be able to use the app.get() without any problem.
Example:
//app.js
var express=require('express');
var app = express();
app.set('multimedia', __dirname + '/public/multimedia');
app.get('/',function(req,res){
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Listening at http://%s:%s', host, port);
});
module.exports=app;
require('./settings');
//settings.js
var app= require('./app');
var dir = app.get('multimedia');
console.log(dir);
More details about module.exports can be found here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With