如何将Node.js文件拆分为多个文件 [英] How to split Node.js files in several files

查看:129
本文介绍了如何将Node.js文件拆分为多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

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!'})
})

我将有很多服务(例如 test 一项),并且我不想将它们全部放在同一个文件中.

I will have many services (like the test one), and I don't want to have them all on the same file.

我在Stack Overflow中读了另一个问题,我可以要求其他这样的文件: var express = require("./model/services.js"); 然后在该文件中写所有服务,但启动Node时会抛出 app未定义.

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.

如何分隔代码?

推荐答案

您可以像这样在 test-routes.js 这样的不同文件中定义路由:

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!'})
    })
}

现在在主文件中说 server.js ,您可以像这样导入路由文件:

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

这篇关于如何将Node.js文件拆分为多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆