Prerequisites
- Node.js installed in your system Nodejs website
- Here is a mini tutorial on how to install Node.js in your system
- type
node -v
in terminal to check if it is installed
Lets write your first line of code
open up your terminal make a directory hello-modules
mkdir hello-modules
cd hello-modules
npm init -y
it will generate a file named
package.json
{ "name": "hello-modules", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
now create two new files
first one ->hello-modules/index.js
is it necessary to create a file with the same name mentioned in package.json
"main": "index.js"
? NO.
If you are not going to publish it to npm usingnpm publish
This field"main"
does not serve any purpose.
second one ->hello-modules/universe.js
and your directory will look like
/** * hello-modules * -- index.js * -- package.json * -- universe.js */
write some code in
hello-modules/index.js
console.log('hello modules from index.js')
then in terminal type
node index.js
*make sure your terminal is in current directory ...\hello-modules>
your terminal would give output
hello modules from index.js
Woohoo, your javascript code now runs in the terminal.
That's why Node.jsยฎ is called JavaScript runtime.
Now its time for fancy stuffs like
module.exports
& require()
Let me clear you a few things before we go ahead
When you start doing cool stuffs with javascript in terminal instead of browser.
you write javascript code in file like index.js
, that file is known as a module.
Now there are two types of modules
- CommonJs module
- ECMAScript module
by default node supports Commonjs module system
What it feels like writing code in CommonJS module system
you can communicate between two files ( modules ) and use one another codes, functions, classes
go to
hello-modules/universe.js
// declare a const const milkyWay = " it has billions of stars " // and export it with a magic spell module.exports = milkyWay;
in
hello-modules/index.js
// magic spell to get that const from another file (module) // is to make that module (file) available in this file first const milkyWaySomeWhereElse = require('./universe.js'); // now console it to terminal console.log(milkyWaySomeWhereElse);
- now in terminal type
node index.js
- will give output like
it has billions of stars
Congrats ๐, You just used two magical spells
exports
andrequire
Lets do some experiments ๐งช
Experiment #1
clear everything from
hello-modules/universe.js
& make it empty
and inhello-modules/index.js
writeconst milkyWaySomeWhereElse = require('./universe.js'); console.log(milkyWaySomeWhereElse);
in terminal type
node index.js
it will give output like
{}
Experiment #2
in
hello-modules/universe.js
writeconst solarSystem = "It has a planet called Earth"; const pandora = "this planet exists in movie Avatar"; module.exports.solarSystem = solarSystem; module.exports.pandora = pandora; // you can remove module. from above lines // exports.solarSystem = solarSystem; // module.exports.pandora = pandora; // they will work the same way
then in
hello-modules/index.js
keep it sameconst milkyWaySomeWhereElse = require('./universe.js'); console.log(milkyWaySomeWhereElse);
in terminal type
node index.js
you will get an output
{ solarSystem: 'It has a planet called Earth', pandora: 'this planet exists in movie Avatar' }
from this experiment, what I conclude is
if we export from a module (file) like
module.exports.solarSytem = solarSystem
module.exports.pandora = pandora
and require from another file (module)
const milkyWaySomeWhereElse = require('./universe.js')
we get an object with keyspandora
andsolarSystem
- and we access them like we do with objects (Associative Array)
// either by dot Notation const pandora = milkyWaySomeWhereElse.pandora; const solarSystem = milkyWaySomeWhereElse.solarSystem; // or from bracket Notation const pandora = milkyWaySomeWhereElse["pandora"]; const solarSystem = milkyWaySomeWhereElse["solarSystem"]; // or by destructuring assignment // most popular one used in modules while importing const { pandora, solarSystem } = milkyWaySomeWhereElse; // most of the times you will see const { pandora, solarSystem } = require('./universe.js');
Experiment #3
- in
hello-modules/universe.js
writeconst solarSystem = "It has a planet called Earth"; const milkyWay = " it has billions of stars " module.exports.solarSystem = solarSystem; module.exports = milkyWay;
keep
hello-modules/index.js
sameconst milkyWaySomeWhereElse = require('./universe.js'); console.log(milkyWaySomeWhereElse);
in terminal type
node index.js
- the output you will get is
it has billions of stars
from this experiment, what I conclude is
in
hello-modules/universe.js
module.exports = milkyWay;
only this line worked and milkyWay got exportedwhatever you put in place of milkyWay get exported as it is from that whole file (module), leaving other exports like
module.exports.solarSystem = solarSystem
useless- In above two experiments, we have seen a file (module) exports a object.
It is not always the case.
Experiment #1 and #2 were special cases. - You can export anything from a module ( lets say from
hello-modules/universe.js
) usingmodule.exports = anything
. And require ( import that module) from
hello-modules/index.js
likeconst milkyWaySomeWhereElse = require('./universe.js'); console.log(milkyWaySomeWhereElse);
in
hello-modules/universe.js
module.exports = "you can export a string";
milkyWaySomeWhereElse
will be equal to"you can export a string"
module.exports = ["an", "array", "with", 1, "boolean", "value", true];
now
milkyWaySomeWhereElse
will be equal to["an", "array", "with", 1, "boolean", "value", true]
module.exports = { sky:"it is blue", hello:"you can export a object" };
In this case
milkyWaySomeWhereElse
will be equal to
{ sky:"it is blue", hello:"you can export a object" }
module.exports = function(){ return "you can a export a function which returns some value"; } // or // module.exports = function(){ // console.log("you can a export a function which do not returns any value"); // }
milkyWaySomeWhereElse
is a function now
the function is declared only and get assigned to another variable,
but not called yet!
or not executed yet
This function is same as normal functions in javascript,
to call or execute write
milkyWaySomeWhereElse()
console.log(milkyWaySomeWhereElse())
will output the string
"you can a export a function which returns some value"
In
hello-modules/universe.js
you can export a class.class Planet { constructor(name) { this.name = name; } getName() { return this.name; } sayHiTo(name) { console.log(`Hi ${name}, I'm ${this.name}`); } } module.exports = Planet;
from
hello-modules/index.js
const Planet = require('./universe.js'); const mars = new Planet('Mars'); console.log(mars.getName()); mars.sayHiTo('Elon Musk');
- in terminal type
node index.js
- output would be like
Mars Hi Elon Musk, I'm Mars
Its your turn ๐ฏ
I have written a coding-challenge based on this topic.
- Go ahead make modules ( javascript files ) and practice with this coding challenge.
- Do cool stuffs.
- Happy Learning !
NOTE: I will write about ECMAScript (ES6) modules in next post.