In Node.js, how do I “include” functions from my other files?

后端 未结 25 2572
猫巷女王i
猫巷女王i 2020-11-22 04:22

Let\'s say I have a file called app.js. Pretty simple:

var express = require(\'express\');
var app = express.createServer();
app.set(\'views\', __dirname + \         


        
25条回答
  •  鱼传尺愫
    2020-11-22 05:00

    You can simple just require('./filename').

    Eg.

    // file: index.js
    var express = require('express');
    var app = express();
    var child = require('./child');
    app.use('/child', child);
    app.get('/', function (req, res) {
      res.send('parent');
    });
    app.listen(process.env.PORT, function () {
      console.log('Example app listening on port '+process.env.PORT+'!');
    });
    
    // file: child.js
    var express = require('express'),
    child = express.Router();
    console.log('child');
    child.get('/child', function(req, res){
      res.send('Child2');
    });
    child.get('/', function(req, res){
      res.send('Child');
    });
    
    module.exports = child;
    

    Please note that:

    1. you can't listen PORT on the child file, only parent express module has PORT listener
    2. Child is using 'Router', not parent Express moudle.

提交回复
热议问题