Node Js-1

Node Js-1

-- node js is a javascript runtime environment that runs JS outside the web browser.

we can run node js in

-REPL ( read-eval-print-loop),

-CLI (command line interface)

COMMON JS MODULE :

DEFAULT EXPORTS:

--how to export one module also called (default exports) that allows us to export only one property.

{ const add = ()=> a+b;

module.exports = add ( exporting a module )

(add is a function that returns a value )

-- const add = require("./calculator") (importing a module)

-- importing from another module called calculator module to another one.

Note : "calculator" is a module name where add function is located.

}

NAMED EXPORTS:

--What if we need to export multiple functions at once

we use (named exports ) to export multiple properties

EXPORTING:

module.exports.add = add;

module.exports.sub = sub;

-we can also use shorthand for this -

exports.add = add;

exports.sub = sub;

--here we exported multiple functions from one module so we can use them in another module.

NOTE : if we don't export we can't use them in another module.

-IMPORTING:

{

-- When importing a module it returns an object

-- We can use obj destructing while importing multiple modules.

const cal = require("./calculator")

const {add, sub} = cal;

console.log(add(2, 3))

(calling a function from another module named calculator to another as shown above).

ES6 MODULES

In general, ES6 modules are considered to be a more modern and efficient way to modularize JavaScript code.

exporting modules:

default exports:

export default add;

(exporting only one function)

named exports

we can declare what we want to export before define a function.

export const add = (a,b) => a+b;

export const sub = (a,b) => a-b;

IMPORTING MODULES:

import {add , sub} from "./calculator.mjs"

NOTE: ES6-module is considered when that module extension ends with "mjs"

while importing we need to use an extension in order to import it.

<< Thanks for reading />>