ES6 vs Common Javascript in node js
learn about Es6 modules and common js, after this no doubt
ES6 modules are asynchronous loaded while,
Common js modules are synchronous loaded
How to work with common js
const fs = require("fs")
const fd = rs.readFileSync("filename.txt", "utf-8")
console.log(fd)
// output: filename.txt (// the content will be displayed )
How to work with ES6
import fs from "fs"
const fd = fs.readFile("filename.txt", "utf-8")
console.log(fd)
// output: content of file will be displayed
// NOTE: FOR ES6 FILENAME SHOUDL BE
FILENAME.mjs
Now forget about the common js module, in the Recent rends you only have to deal with ES6 module
Default method for one Function
// add.js function add(a, b){ return a+b; } export default add TODOD: index.mjs // TODO: FOR single acces import addNumber from "filename.mjs" console.log(addNumber(2,3));
More than one, function or component
```javascript function add(a, b){ return a+b; }
function sub(a, b){ return a-b; }
// NOTE: THIS IS NOT AN OBJECT export { add, sub }
// IN index.mjs import {add} from "filename.mjs" import {sub} from "filename.mjs"
console.log(add(5,5)); console.log(sub(5,5));
3. **use as Method in Es6 module**
```javascript
function add(a, b){
return a+b;
}
function sub(a, b){
return a-b;
}
// NOTE: THIS IS NOT AN OBJECT
export {
add,
sub
}
// IN index.mjs
// here we can use are export ,by diffent names as we want
import {add as addTwoNumber} from "filename.mjs"
import {sub as subTwoNumber} from "filename.mjs"
console.log(addTwoNumber(5,5));
console.log(subTwoNumber(5,5));
you can directly export the function(), variable and almost everything
export function sub(a, b){ return a-b; } export isUserLoggedIn = true; // and use them , in two ways... import {sub} from "filename.mjs" import {sub as DirectlySub} from "filename.mjs" console.log(`this is directly exported ${Sub(5,5)}`); console.log(`this is directly exported ${DirectlySub(5,5)}`);
you can import everything together,
// filename.js function add(a, b){ // see if this function is not exported , than no issue return a+b; } export function sub(a, b){ // only this function can be asscisible from outside return a-b; } // if you want import it import * as everyExportFunction from "filename.mjs" console.log(`every exported use in once ${everyExportFunction}`); console.log(everyExport); NOTE: // and after that use (.), // you can access specific function or object console.log(`Subtrat ALl in Once : ${everyExportFunction.sub(40,40)}`);
Thank youe!
CHIRAG KUMAR
Subscribe to my newsletter
Read articles from CHIRAG KUMAR directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
CHIRAG KUMAR
CHIRAG KUMAR
Full stack Developer