How To Read & Write File In Node.js

Share Now

//FS STANDS FOR File System 
const fs = require('fs');

//BLOCKING SYNCHRONOUS WAY
const textIn = fs.readFileSync('./txt/input.txt', 'utf-8');
//WILL READ THE FILE & SHOW IN CONSOLE
//console.log(textIn);

const textOut = `This is NMH47 Talking About Avacado: ${textIn}.\nCreated on ${Date.now()}`;
fs.writeFileSync('./txt/amar-output.txt',textOut);
//WILL CONFOIRM THAT FILE IS WRITTEN
//console.log('File Written');


const textShow = fs.readFileSync('./txt/amar-output.txt','utf-8');
//WILL READ THE FILE & SHOW IN CONSOLE
console.log(textShow);


//NON-BLOCKING ASYNCHRONOUS WAY
fs.readFile('./txt/start.txt', 'utf-8',(err, data) => {
    console.log(data);
});

const data2 = 'Sherlock';
const data3 = 'Holmes';

fs.writeFile('./txt/nexus.txt',`${data2} ${data3}`,'utf-8', err => {
    console.log('Fille has been written successfully');
});

fs.readFile('./txt/nexus.txt','utf-8', (err, data) => {
    console.log(data);
});
Picture of Nahid Mahamud

Nahid Mahamud

Web Developer | Graphic Designer | WordPress & Woo-commerce Expert