How to split Node.js files in multiple files

I have this code:

var express = require("express");
var app     = express();
var path    = require("path");

app.use(express.static(__dirname + '/public'));

app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/views/index.html'));
  res.set('Access-Control-Allow-Origin', '*');
}).listen(3000);

console.log("Running at Port 3000");

app.get('/test', function(req, res) {
    res.json(200, {'test': 'it works!'})
})

I will have many services (for example, testone), and I do not want all of them to be in one file.

I read in another question on Stack Overflow that I might need other files: var express = require("./model/services.js");And in this file write all the services, but it throws app is not definedwhen Node starts up.

How can I separate the codes?

+4
source share
2 answers

You can define your routes in different files, say test-routes.js, like this:

module.exports = function (app) {
    app.get('/test', function(req, res) {
        res.json(200, {'test': 'it works!'})
    })
}

Now in your main file say server.js, you can import the route file as follows:

var express = require("express");
var app     = express();
var path    = require("path");

app.use(express.static(__dirname + '/public'));

app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/views/index.html'));
  res.set('Access-Control-Allow-Origin', '*');
}).listen(3000);

console.log("Running at Port 3000");

// import your routes
require('./test-routes.js')(app);
+6
source

test.js :

var express = require('express');
var router = express.Router();

router.get('/test', function (req, res) {
  res.json(200, {'test': 'it works!'});
});

module.exports = router;

app.js (, - , test.js):

var test = require("./routes/test.js");
var other = require("./routes/other.js");
...
//all your code for creating app 
...
app.use('/test', test);
app.use('/other', other);
+3

Source: https://habr.com/ru/post/1617665/


All Articles