Node.js: Server.js is getting cluttered with functions
I have a server.js
with many functions.
app.post '/record2', (req,res) ->
app.post '/record', (req,res) ->
app.post '/incoming', (req,res) ->
app.post '/call', (req,res) ->
etc..
It's starting to become very confusing. What's the best way to make the server.js cleaner 开发者_如何学JAVAand easier to understand?
Thanks
I assume you're using Express? Something I've done in the past is create modules for related handlers. E.g.,
Something like this in record-handlers.js
:
module.exports = {
record2: function(req, res) { ... },
record: function(req, res) { ... }
};
And then in server.js
:
var recordHandlers = require('./record-handlers');
app.post('/record2', recordHandlers.record2);
app.post('/record', recordHandlers.record);
...
*My apologies for converting your Coffeescript to JS - I don't know CS at all.
As you can see here (lines 231 through 235.)
switch (config.method) {
case 'GET': server.get(config.path, internals.preprocessRequest, routes, config.handler, internals.finalizeResponse); break;
case 'POST': server.post(config.path, internals.preprocessRequest, routes, config.handler, internals.finalizeResponse); break;
default: process.exit(1); break;
}
the routes and the handlers are in different modules.
Another strategy would be to use a catch-all route like this :
/:action
and use a switch statement to call the required function based on the value of
req.param('action')
精彩评论