Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create modules for Node.js?

Tags:

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()?

like image 553
dail Avatar asked Jun 07 '11 18:06

dail


People also ask

Can we create our own module in node JS?

To create a module in Node. js, you will need the exports keyword. This keyword tells Node. js that the function can be used outside the module.

What are modules in node JS?

In Node. js, Modules are the blocks of encapsulated code that communicates with an external application on the basis of their related functionality. Modules can be a single file or a collection of multiples files/folders.


1 Answers

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); 
like image 79
Alnitak Avatar answered Oct 13 '22 14:10

Alnitak