javascript - Modular programming in node js -


in our node js application, api calls in server.js. working application, i'm not happy every api written in 1 file i.e. server.js. many of examples related node js application, point writing server side calls in 1 file named app.js or server.js. achieve code modularity, i'm planning separate api's in different files employee.js (employee related data transaction), library.js (library related data transaction) , on respective modules. not sure whether right approach node.js server needs launched on application invoke. so, if api's distributed different files need check how launch node js server in 1 shot.

also, have integrated node-webkit application.

need suggestions in regard.

one of greatest things in node.js module system (you can read in docs: https://nodejs.org/api/modules.html), gives every option of granularity take, one-thousand-lines files files export 1 constant.

so split code in files, module.exports = thatthingyouwanttoexport , require('./it') in app.js. if @ top-level, not inside callback in app.js, done right @ start of application.

few catches:

  • required modules cached, requiring twice doesn't execute files twice, can useful (e.g. singletons), it's still thing note;
  • you export things you're exporting, no globals

one useful pattern export function, takes arguments , initialization when called, this:

//accum.js var start = 0 module.exports = function initaccum(step) {     return function accum() {         start += step;         return start;     } }  //app.js var accum = require('./accum.js')(1); var http = require('http') http.createserver(function(req, res) {     res.end(accum()); }).listen(8080); 

hope helps.


Comments