Let’s have a look at how to organize the application containing code for a very basic HTTP server:
var http = require("http"); function onRequest(request, response){ response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World !!!"); response.end(); } http.createServer(onRequest).listen(port, host);
Now, let’s turn this code into a real NODE.JS module that can be used by the main script.
As you may have noticed, the modules are used in the code as follows:
var http = require("http"); ... http.createServer(…);
In NODE.JS there is a module called “http” that can be used in the code by requiring and assigning the result of this requirement to a local variable. This turns the local variable into an object carrying all the public methods that the “http” module provides.
It is common practice to use the module name as the local variable name; however, you may choose whatever you like:
var foo = require("http"); ... foo.createServer(...);
Now it should be clear how to use internal NODE.JS modules.
To create and use your own modules, you do not have to change very much. Making some code for a module means that you need to export the parts of its functionality that you want to provide with scripts requiring this module.
For now, the functionality that the HTTP server needs to export is simple: scripts requiring the server module simply need to start the server.
To make this possible, put your server code into a function named start() and export it:
var http = require("http"); function start() { function onRequest(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World !!!"); response.end(); } http.createServer(onRequest).listen(8888); } exports.start = start;
Now you just save this code into the new folder with name server and name it “server.js”. You can start the HTTP server from the main or timed scripts:
var server = require("server"); server.start();