Modules
First, we create a javascript file like index.js after that install the package.json file by using the npm init command in the terminal.
After, executing the npm init command a file will appear in front of your dashboard. like this:-
{
"name": "modules",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Inside the above code, it summarizes the name of the module, version, dependencies .... etc. Inside "scripts"
we can use many key values that contain a "start":" node index.js"
, which means in the terminal when we write npm start index.js
file is executed.
we can also replace the "start"
key by using any other name like this "Youtube":" node index.js"
, in this case when we execute the file then you will write npm Youtube index.js
then the file will be executed.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start":"node index.js"
},
When we declare a function and we want to access that function in another file, at that scenario we use the module the function which you want to access in another file first you export that function using this syntax:
function add(a, b){
return a + b;
};
module.exports ="piyush";
//Or
module.exports ={
add, sub, multiply
}
If you want to export more than one function(anything) then we use an object like this:- module.exports ={}
inside curly brackets we use multiple functions which are given in the above examples.
where we use that function use the above code, in this required() function is
const math = require('./math');
Inside the required() function parameter we provide a path of the file or we can also use a built-in package inside the parameter.
When we export the file using module.exports={}
inside the javascript object if we want to change the name of a function then we can also change the function name in this way:-
module.exports = {
addfun:add,
subfun:sub
};
Now we can access that function in this ways:-
const math = require('./math');
console.log(math.add(10,20));
If you want to export only one file then we can also use this way
exports.add =(a,b)=>a+b;
exports.sub =(a,b)=>a-b;