Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split monolithic node.js javascript

I have a growing node.js server application, and I'd like to get it split into several files. Here is a working code snippet demonstrating what monolithic server.js roughly looks like:

var express = require('express');
var app = express();
// other initialization code etc

//************** start of part to be moved foo.js

var fooTestData = {data: "data", id:1};

app.get("/foo/ajax", function(req, res) {
    res.json(fooTestData);
});

// more REST stuff and other foo-specific code

//************** end of part to be moved

// more stuff which remains in server.js

// http://localhost:8888/foo/ajax
app.listen(8888);

An ideal answer has two pieces of code with identical functionality: What server.js looks like after moving the indicated part, and what foo.js looks like with copied code and any needed extra code.

like image 625
hyde Avatar asked Oct 15 '25 14:10

hyde


2 Answers

foo.js

var fooTestData = {data: "data", id:1};

exports.setApp = function (app) {

    app.get("/foo/ajax", function(req, res) {
        res.json(fooTestData);
    });

    // more REST stuff and other foo-specific code
};

new sever.js

var express = require('express');
var app = express();

require('./foo.js').setApp(app);

// other initialization code etc


// more stuff which remains in server.js

// http://localhost:8888/foo/ajax
app.listen(8888);

It's a simple example. If you need some things more complex you may want to take a look to other express program on github. It could be a good source of inspiration.

like image 172
peernohell Avatar answered Oct 17 '25 03:10

peernohell


I recommend you to have a look at some express-based (MVC) frameworks. Have a look at the list of frameworks. Moreover, you might want to check sails.js (express based framework) if you are doing a webservice and communicating with it via RESTfull requests. Please note that sails is not limited to RESTfull requests and can help you scale your project out of the box.

Good luck!

like image 35
eAbi Avatar answered Oct 17 '25 03:10

eAbi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!