How to create modules for Node.js?

I have a simple code:

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

I would like to put this code into server.js. This code has to be a MODULE that has many internal functions. I would like to create server module and listen() function inside it.

I should put createServer() inside a function called listen().

If I have index.js how can I call this module and then do something like server.listen()?

The common pattern for nodejs modules is to create a file (e.g. mymodule.js) so:

var myFunc = function() {
   ...
};

exports.myFunc = myFunc;

If you store this in the directory node_modules it can be imported thus:

var mymodule = require('mymodule');

mymodule.myFunc(args...);

So, in your case, your module server.js could look like this:

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

which would be invoked:

// client.js
var server = require('server');
server.listen(8000);

Old post, but if someone is still interested in I would suggest following solution:

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

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


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   ES5 vs ES6 Promises

Similar Posts