Reputation: 4481
app.js:
var app = express();
require('./other_file.js')(app);
other_file.js:
app.post('/test', function(req, res) {
console.log(true);
});
result: app is not defined.
How to use express methods in require file?
Thanks in advance.
Upvotes: 0
Views: 43
Reputation: 62412
You have to specifically export the member you want to expose with a require.
other_file.js
should look like this
module.exports = function(app) {
app.post('/test', function(req, res) {
console.log(true);
});
}
where module.exports
is the member that is returned when the file is used with a require()
statement.
Node itself borrows from the CommonJS module spec.
Upvotes: 1
Reputation: 30733
other_file.js
should be something like that:
module.exports = function(app) {
app.post('/test', function(req, res) {
console.log(true);
});
}
Longer story:
when you require()
a file you get back an object (the exports
object). If you want to get back a function you need to make your function replace the exports object. To achieve that you need to assign your function to module.exports
Upvotes: 2