How do you modularize Node.JS w/Express
I'm trying to modularize my node.js application (using express framework). The trouble I am having is when setting up my routes.
I am no longer able to extract the data I send to the post. (req.body is undefined). This works okay if it is all in the same file. What am I doing wrong here, and what is the best way to modularize code in node.js?
My app.js
require('./routes.js').setRoutes(app);
My route.js
exports.setRoutes = function(app){
app.post('/ask', function(req开发者_如何学JAVA, res, next){
time = new Date();
var newQuestion = {title: req.body.title, time: time.getTime(), vote:1};
app.questions.push(newQuestion);
res.render('index', {
locals: {
title: 'Questions',
questions: app.questions
}
});
});
A better approach:
Create a routes.js file that contains:
var index = require('./controllers/index');
module.exports = function(app) {
app.all('/', index.index);
}
Then, from within your server.js (or however you've started your server), you'd require it as such:
require('./routes')(app);
This way you aren't creating global variables that bring with them a whole slew of issues (testability, collision, etc.)
I realize someone already answered but here's what I do anyway.
app.js :
fs.readdir('./routes', function(err, files){
files.forEach(function(fn) {
if(!/\.js$/.test(fn)) return;
require('./routes/' + fn)(app);
});
});
./routes/index.js :
module.exports = function(app) {
var data_dir = app.get('data-dir');
app.get('/', function(req, res){
res.render('index', {title: 'yay title'}
});
}
Maybe someone will find this approach helpful.
My issue was that I was declaring app in the wrong way. Instead of var app = module.exports = express.createServer();
, it should have just been app = express.createServer();
And then all I needed to do in my app.js was require('./routes.js');
. Now the routes file has access to the app variable and now I can just declare routes normally in the routes file.
(routes.js)
app.get('/test', function(req, res){
console.log("Testing getter");
res.writeHead('200');
res.end("Hello World");
});
global "app" for me (usually). If you know the app wont be require()d, and if you're not clumsy it's a lot easier to work with
example in app.js
var users = require('./lib/users'); //this is your own module
app.use(users);
then, you in your lib/users folder, create files ( index.js,user.ejs,etc). use index.js for default module load //index.js var express = require('express'); var app = module.exports = express();
app.set('views',__dirname);
app.set('view engine','ejs');
app.get('/users',function(req,res){
//do stuffs here
});
I made an example of Modular node.jes + Boostrap here : Nodemonkey or a tutor here here
精彩评论