Created
April 9, 2015 20:17
-
-
Save fluxrad/90b3478efc75f9cf3330 to your computer and use it in GitHub Desktop.
Dynamically requiring module in NodeJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.index = function(req, res) { | |
res.send('This is bar!'); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.index = function(req, res) { | |
res.send('This is foo!'); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var app = express(); | |
app.get('/', function(req, res) { | |
res.send('Hi2u'); | |
}); | |
// dynamically require modules. | |
app.get('/:foo', function(req, res) { | |
if (['foo', 'bar'].indexOf(req.params.foo) >= 0) { | |
var foo = require('./lib/' + req.params.foo); | |
foo.index(req,res); | |
} | |
else { | |
res.send('endpoint not found'); | |
} | |
}); | |
var server = app.listen(3000, function () { | |
var host = server.address().address; | |
var port = server.address().port; | |
console.log('Example app listening at http://%s:%s', host, port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment