2017-04-06 78 views
-1

我正在学习node.js,并且我遇到了这种方式将我的服务器文件拆分为不同的文件,以便更好地维护它。Node.js将服务器文件划分为单独的文件

问题是,我已经看过所有这些老办法将文件分成几个文件。 例如为: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

但所有这些方法不工作了,他们已经过时。现在我正试图找到一种方法,我们现在可以分割文件。这不是在这里,也不是在谷歌。现在我找了好几个了一个多小时,我无法找到这样做的正确方法..

回答

0

你很可能使用(需要)标签,包括您的文档中的Node.js

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

只是把它们放在正确的地方

1

这些链接绝对有效。下面是一个例子

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.

0

如果你有一个文件,例如server.js这样的:

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

function b() { 
    a(); 
} 

b(); 

然后你就可以像这样把它分解:

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; 

查看文档的更多信息:

另见这个答案并说明如何做你想要什么更复杂的情况比我这里显示:

也看到那些回答一些有趣的细节:

0

我得到它的工作。比如下解决办法:

文件:

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.'); 
    }); 
}; 
+0

你可以看看快车中间件代替(而不是“路线(路由)') –

相关问题