Node Js REPL, Core Modules , File System using synchronous and Asynchronous method

Node JS REPL

    The REPL feature of NodeJS is very useful in experimenting with Node.js codes and to debug JavaScript codes.

see more

Read Reads user's input, parse the input into JavaScript data-structure
Eval Takes and evaluates the data structure
Print Prints the result
Loop Loops the above command until the user presses ctrl+c twice
Core Module
  • Node.js has a set of built-in modules which you can use without any further installation. like fs, http, https, os, path, util.... etc.
using synchronous method: 
        synchronous means to be in a sequence, i.e. every statement of the code gets executed one by one. So, basically a statement has to wait for the earlier statement to get executed.

  • fs is a build in module it help to store, access, and manage data on our operating system.
  • writeFileSync - it help to write data in synchronous manner. if 'index.txt' is not found or nothing, so it created automatically. 
  • readFileSync - it help to read file data. 
const fs = require("fs");

// write data
fs.writeFileSync("index.txt","hey i'm shreyash");

// read file data
const data = fs.readFileSync("index.txt")
console.log(data)

const newData = data.toString();
console.log(newData)
PS F:\nodejs> node app.js
<Buffer 68 65 79 20 69 27 6d 20 73 68 72 65 79 61 73 68>
PS F:\nodejs> node app.js
<Buffer 68 65 79 20 69 27 6d 20 73 68 72 65 79 61 73 68>
hey i'm shreyash
NodeJs include an additional data type called as buffer
Buffer is  mainly used to store binary data, while remaining from a file or receiving packets over the network. 
for avoiding buffer data so used 'utf-8' it help to Encodes any given JavaScript string as UTF-8, and returns the UTF-8-encoded version of the string

// rename file
fs.renameSync("index.txt", "read.txt");
fs.appendFileSync("index.txt", "today is awesome day");
using asynchronous method:
        Asynchronous code allows the program to be executed immediately
const fs = require("fs");

// create and write file
fs.writeFile("read.txt", "today is awesome day",(err)=>{
    console.log("file is created")
    // console.log(err)
})

// read file
fs.readFile("read.txt","utf-8", (err, data)=>{
    console.log(data);
})
PS F:\nodejs> node app.js
file is created
today is awesome day
append file
//append file
fs.appendFile("read.txt","\n hey i'm shreyash",(err)=>{
    console.log("task completed")
})