我有一个简单的代码:
var http = require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type" : "text/html"});
response.write("Hello World");
response.end();
});
server.listen(8000);
console.log("Server has started.");
我想将此代码放入server.js。此代码必须是具有许多内部功能的MODULE。我想在其中创建server
模块和listen()
函数。
我应该将createServer()
放在名为listen()
的函数中。
如果我有index.js,我如何调用此模块然后执行类似server.listen()
的操作?
答案 0 :(得分:57)
nodejs模块的常见模式是创建一个文件(例如mymodule.js
),所以:
var myFunc = function() {
...
};
exports.myFunc = myFunc;
如果将其存储在node_modules
目录中,则可以导入它:
var mymodule = require('mymodule');
mymodule.myFunc(args...);
因此,在您的情况下,您的模块server.js
可能如下所示:
// server.js
var http = require("http");
var listen = function(port) {
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type" : "text/html"});
response.write("Hello World");
response.end();
});
server.listen(port);
};
exports.listen = listen;
将被调用:
// client.js
var server = require('server');
server.listen(8000);
答案 1 :(得分:4)
旧帖子,但如果有人仍然感兴趣我会建议以下解决方案:
//server.js
var http = require("http");
// As soon as method will be used outside the module, use "this":
this.listen = function(port) {
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write("Hello World");
response.end();
});
server.listen(port);
};
//index.js
var module = require('./server');
module.listen(8000);
答案 2 :(得分:3)
// main.js
var server = require("server");
server.listen(8000);
console.log("Server has started.");
// server.js
var http = require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {
"Content-Type": "text/html"
});
response.write("Hello World");
response.end();
});
module.exports = server;