In our previous tutorial, we used a core module of Node.js, the http module. You can think of core modules as built-in modules of Node.js. However, we can also write modules of our own. To understand the story behind these modules, let's go ahead and make one.
When writing a web app, instead of writing all the code in a single JavaScript file, we can group and split the code into smaller meaningful parts. One such chunk of code is called a module. Use of modules give us extensible and reusable code. So let's go step by step and make one.
Step1 - Writing a new Module
Create a new JavaScript file, "kid.js". Let's think that the only things that this kid can do are eating and drinking. We can write two simple JavaScript functions to mimic this.What is important to notice here is that we have to export these functions, in order to use them in another module.
It is possible to export variables or functions from a module. There are also other methods of exporting functions. For now, understanding this will suffice.
function eatFood() {
return 'I am eating\n';
}
function drinkTea() {
return 'I am drinking\n';
}
module.exports.eat = eatFood;
module.exports.drink = drinkTea;
The last two lines of this code snippet shows you how to do that.For example, we export the eatFood() function as eat(). So this function can be called by another module only by calling eat(), not eatFood().
Step2 - Importing module
We can import a module to our app, "app.js", similar to importing the http core module. We simply have to use the require() method.var http = require('http');
var kid = require('./kid');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(kid.eat());
res.write(kid.drink());
res.end();
}).listen(9000);
console.log('Server running at http://127.0.0.1:9000/');
Step3 - View Result
Start our server by typing the following command in the terminal.$ node app.js
No comments:
Post a Comment