Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

javascript - How to split Node.js files in several 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 (like the test one), and I don't want to have them all on the same file.

I read in another question in Stack Overflow, that I can require other files like this: var express = require("./model/services.js"); And in that file write all the services, but it's throwing app is not defined when I start Node.

How can I separate codes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 your route file like this:

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...