04 - File_System in NodeJS

// Creating/Editing/Reading a file with NodeJS:
//
// First, require the file system module:
    
    const fs = require('fs');
    

// require the path module:
    
    const path = require('path');
    

// mention the fileName with path:
    
        const abc = path.join(__dirname, 'files', 'abc.txt');

    // __dirname represents path to this file
    // we can use path.join to combine the currentpath with files and abc.txt,
    // it will make abc = 'currentPath/files/abc.txt'
    

// Data to be written in the file:
    
    const data = "Hello from File System.";
    

// Creating/Editing the file:
    
    fs.writeFile(abc, data, {
        encoding: 'utf-8',
        flag: 'w'
    }, (err)=>{
        if(err){
            throw err;
        }
        console.log('File written successfully.');
    });
    

// Reading from the File:
    
    fs.readFile(abc, (err, data)=>{
        if(err){
            throw err;
        }
        console.log(`File Content: ${data.toString()}`);
    })
    
// see below file for the complete code:
index.js

//--------------------------------------------------------------------------------------------------

// Now let's solve a programming question involving File System:
// Q. there are two files: input1.txt and input2.txt
//      both contain a list of numbers
//      we need to get these lists of numbers and sort them
//      then put that sorted combined list in output.txt

// A. Read from input1.txt and input2.txt
    input1.txt
    input2.txt    
//      create a combined list of numbers,
//      sort the list,
//      write the sorted list in output.txt
    sort.js
    output.txt