-1

I am learning for node.js and i came across this way to split my server file into different files so its better maintainable.

The problem is, i have looked at all these old ways to split the files into several files. e.g.: How to split monolithic node.js javascript

Divide Node App in different files

How to split a single Node.js file into separate modules

How to split Node.js files in several files

but all these methods do not work anymore, they are outdated. and now i am trying to find a way that we can split files now. Which isnt here.. nor its in google. I am looking for it for over an hour now and i cannot find the right way to do this..

Community
  • 1
  • 1
Alex
  • 789
  • 1
  • 6
  • 13
  • while Express.js is not the same as Node.js, they provide [documentation](http://expressjs.com/en/guide/routing.html) showing how they do it which you might find helpful. Also [MDN](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/routes). – Ronnie Royston Dec 20 '18 at 19:46

4 Answers4

4

Those links definitely work. Here is an example

greeter.js

module.exports = {
    hello: function(name) {
        console.log("Hello, " + name);
    },
    bye: function(name) {
        console.log("Goodbye, " + name);
    }
};

index.js

var greeter = require('greeter');

greeter.hello("Foo");
greeter.bye("Bar");

Here is the Node.js documentation for it.

Austin Winstanley
  • 1,339
  • 9
  • 19
1

I got it working. The solution was as followed:

Files:

server.js (root dir)
routes.js (root dir/routes/routes.js)

Server.js

var express = require('express');
var app     = express();
var routes = require('./routes/routes');

app.listen(3001);
routes(app);
console.log('Started listening on port : 3001');

routes.js

module.exports = function(app) {
    app.get('/', function(req, res) {
        res.end('test');
        console.log('Received GET request.');
    });
};
Alex
  • 789
  • 1
  • 6
  • 13
0

you could probably use the (require) tag to include your documents in node.js

require('/home/user/module.js');

just put them on the right places

King Reload
  • 2,780
  • 1
  • 17
  • 42
0

If you have a file, e.g. server.js like this:

function a() {
  console.log('This is a()');
}

function b() {
  a();
}

b();

Then you can split it like this:

server.js:

const b = require('./b');

b();

b.js:

const a = require('./a');

function b() {
  a();
}

module.exports = b;

a.js

function a() {
  console.log('This is a()');
}

module.exports = a;

See the docs for more info:

See also this answer does show how to do what you want for more complicated cases than I showed here:

See also those answer for some interesting details:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177