Nodejs File System Notes

Nodejs File System.

Load module with name 'fs'

To Read a file use fs.readFile 

To Write a file use fs.writeFile (Note : if file does not exists it will create the file)

existsSync is used to check if file or folder exists


To create a new directory use fs.mkdir


To remove a directory use fs.rmdir


To delete a file use fs.unlink


To read and write stream from readstream to writeStream just use read.pipe(write), In this case we are using pipe


rdStrea.on('data', callback) this is a event on data - basically it tells to act when data comes


const fs = require('fs');

// Read File asynchronous
fs.readFile('./hello.txt',(err, data)=>{
    if(err) console.log(err)

    console.log(data.toString());
});

// write file asynchronous

fs.writeFile('./hello.txt', 'New Message: Hello India', ()=>{
    console.log('file was written')
});



// check if server directory does not exists, if true then create a new Server directory 
if(!fs.existsSync('./Server')){
    fs.mkdir('./Server', (err)=>{
        if(err)console.log(err);
        console.log('Directory created')
    })
}else{
    // delete if directory exits

    fs.rmdir('./Server',(err)=>{
        if(err)console.log(err);
        console.log('directory deleted')
    })
}

// check if file exists then delete it

if(fs.existsSync('./hello.txt')){
    fs.unlink('./hello.txt',(err)=>{
        if(err)console.log(err);
        console.log('file delted')
    })
}

// Read huge amount of data in chunks using streams
// Write stream data to a new file using writestream

const rdStream = fs.createReadStream('./hugetext.txt',{encoding: 'utf8'});
const wrStream = fs.createWriteStream('./hugetext2.txt');

// read stream data in chunks
rdStream.on('data',(chunks)=>{
    console.log(chunks);
})

// using pipe in node for reading and writing stream of data
rdStream.pipe(wrStream);

6 Problems of Recursion in Javascript with Solution

 In this article I am going to mention 6 Javascript Recursion examples.

How Recursion works.

It basically works by calling same function again and again until it reaches a base case that is usually an if condition and from here it returns.

This example includes following things.

  1. Calculate Factorial of a Number
  2. Print Increasing Decreasing using Recursion 
  3. Sum of N numbers using Recursion
  4. Reverse an array using Recursion
  5. Check if Number is Palindrome 


// Calculate Factorial of a Number e.g 5 ! = 5x4x3x2x1

function findFactorial(n){
    if(n==0){
        return 1;
    }    
  return  findFactorial(n-1) *n;  
}


findFactorial(5);



//  Print Increasing Decreasing e.g 3 2 1 1 2 3
function IncresingDecreasing(n){ if(n<1){ return; } console.log(n) IncresingDecreasing(n-1); console.log(n) } IncresingDecreasing(5); // Sum of N numbers e.g 1 + 2 + 3 + 4 = 10 function sumOfNumbrs(n){ if(n==0){ return 0; } return n + sumOfNumbrs(n-1); } v=sumOfNumbrs(10000); console.log(v); // Reverse an array [1,2,3,4,5] to [5,4,3,2,1] function reverseArray(i,n,arr2=[]){ if(i <= 0){ return; } arr2.push(n[i-1]); reverseArray(i-1,n,arr2); return arr2; } z=reverseArray(15,[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]); console.log(z); // Check if number is Palindrome e.g 2002, Here we will reverse the digits and compare if
// equal then it is palindrome

function reverseDigit(n,arr=[]){

  if(n==0){
    return;
  }
  
  let num1 = n%10;
  let num2 = parseInt(n/10);
  arr.push(num1);
  
  checkIfNumberPalindrome(num2,arr);
  
  return arr;
  
}

function checkPalindrome(a){
  let reverseArr = reverseDigit(a,[]);
  let revedigit =parseInt(reverseArr.join(''));
  if(revedigit == a){
    return "It is Palindrome";
  }else{
    return "It is not a Palindrome"
  }
}

 let reverse = checkPalindrome(5465464654);
console.log(reverse);

Create and send html file in Nodejs

 Here we will simply create a static file using file module and then send the same file as the response.

To view the result run this file using node app.js then visit localhost:8080 in the browser

const fs = require("fs");
const http = require('http');

const str =`Hello World`;
const html =buildHTML('Hello World Page',str);
const fileName='helloWorld.html';

http.createServer(function (req, res) {
    fs.appendFile(fileName, html, function (err) {
        if (err) throw err;
        console.log('Saved!');
    })     

    fs.readFile(fileName, function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
    });

}).listen(8080);

function buildHTML(title,body){

  let html =`       
        <!doctype html>
        <html lang="en">
          <head>
            <title>${title}</title>
          <body>
            ${body}
          </body>
        </html> 
  `;

  return html;
}

Contact Me

Name

Email *

Message *