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()
?
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With