Node Js

CommonJs vs EcmaScript module :

We gonna learn the difference between the commonjs and EcmaScript(ES). First let us see the basic structure of nodejs :

initialize it as a npm project beforehand with the help of npm init -y

const { createServer } = require('node:http');

const hostname = '127.0.0.1';
const port = 3000;

const server = createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at <http://$>{hostname}:${port}/`);
});

so as default in package.json the type is defined as “commonjs”. Commonjs and Ecmascript differ in style of importing packages let us understand this with the following example :

In Commonjs

let us make two .js files in the code editor and will act as a module and the second is where we will import the function and variable from the module

//module.js
module.exports = {
     a: 1,
     b:4
 }
//main.js
const a = require("./mymodule2.js")

console.log(a, __dirname, __filename)// outputs the value of a, along with the directory and the file name

<aside> 💡

the code is wrapped in a function by default where the parameters like __dirname and __filename is passed so it doesn’t gives an error when we print it out

Ex :

(function(exports, require, module, __filename, __dirname) {

 // Module code actually lives here

});

</aside>

In Ecmascript

It is used in ES6 and above, it is bit more modern and syntax to import the packages is bit like python.

//module.js
export const a = 1 // named export
export const b = 2 // named export
export const c = 3 // named export
export const d = 4 // named export
export const e = 5 // named export
 
const obj = {
    x: 5,
    y: 7
}

export default obj; // default export
//main.js
import {a, b, d} from "./mymodule.js"
console.log(a, b, d)

import ayush from "./mymodule.js"
console.log(ayush) //ayush indicates the default export

<aside> 💡

The default export can be imported using any name

</aside>

Working with files :

Fs

So we are gonna learn about working with files with the help of fs module. There are various functions in fs which will help us in creating , appending files and many more. Below is the code for the same :

const fs = require("fs") 
console.log("starting")
fs.writeFileSync("text.txt", "Harry is a good boy")//writefilesync doesn't work asynchronously,so dont use it

fs.writeFile("text2.txt", "Harry is a good boy2", ()=>{
    console.log("done")
    fs.readFile("text2.txt", (error, data)=>{
        console.log(error, data.toString())
    })
})

fs.appendFile("harry.txt", "harryrobo", (e, d)=>{ //help to append text 
    console.log(d)
})

console.log("ending")