Node Concept 1: Working with modules

Introduction

Hello everyone, this is my first series of blogs on my learnings of Node. I believe in KISS-Keep it Simple and Stupid. This means, the blogs will have just the code and least required explanations. Questions and reviews are always welcomed.

The IDE which I will be using is called VSCode, because it comes with terminal of its own and also I am a fan of Microsoft software products.

In this blog we will try understanding on how to work with modules.

We create two different files called app.js and main.js.

folderStructure.PNG

Inside the tutorial.js, add:

const sum=(num1,num2)=>num1+num2;
const pi=3.14;
class SomeMathObject{
        constructor(){
            console.log('Object created'); 
        }
}
module.exports.sum=sum;
module.exports.pi=pi;
module.exports.SomeMathObject=SomeMathObject;

Now, open the app.js and here add the following code:

const tutorial=require('./tutorial');
console.log(tutorial);
console.log(tutorial.sum(2,3));
console.log(tutorial.pi);
console.log(tutorial.SomeMathObject);

Explaination of app.js

Why the hell did we even create tutorial.js. Answer to that is here, in app.js, we will use the constant, class and the method which we created in the tutorial.js. How are we using them? We first create a const called tutorial which gets the tutorial.js modules. Now what are modules? Remember the class, const and the method we created? Yes, those are modules. We use them here using the new tutorial const which we created. We are using . operator in order to do so and we use console.log to see the output. If you dont know what console.log is, then let me tell you that it is kinda print method but it is in love with the console.

Now how do we see the output?

Open terminal in VSCode, dont know how to do it? C'mon, Google it my geek friend, I am not showing how to find it :-P

terminal.PNG

Here type the following to run the first node program which you have written.

node app.js

This will give the following output.

output.PNG Here, you would see, how the various modules were called from the tutorial.js

But, dont you think, we had to write a lot in tutorial.js to export them. Don't worry my friend, we can make the snippet short too. Just replace the module.exports with this one line and tadaa!! We will still be able to get the modules in some other .js files.

module.exports={sum:sum,pi:pi,SomeMathObject:SomeMathObject}
// module.exports.sum=sum;
// module.exports.pi=pi;
// module.exports.SomeMathObject=SomeMathObject;

I hope you learnt something in this not so formal blog of mine. I am sure I will come up with the next concept soon either here or on my YouTube channel. Till the, stay safe and happy Coding! .