Search code examples
javascriptnode.jsnode-modulesyargs

Fs operations with Yargs


I have to perform some operations with Yargs.For example- 1- Write in a file using fs module and for every write operation need to create a new file, 2-You must take i/p from user as fileName and keep saving fileNames in one array (array part is not done), in one separate text file 3-Next time when user enters the same fileName , if it exists ask again to give new fileName , and then same as Point 1. I am facing issues with point 2, how to write as an array in text file, and how to call 'Please provide the fileName' again if user keeps on giving existing fileName.

So far I have done this-

const argv = require('yargs').argv;
const fs = require('fs');
const readline = require('readline');



const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

if (argv._[0] == 'write') {

    rl.question('Please provide the filename:=>', (fileName) => {
        fs.writeFile('fileNameList.txt', fileName, err => {
            if (err) {
                console.log('Error occured');
                return;
            }
            fs.writeFile(fileName, 'Hello', err => {
                if (err) {
                    console.log('Error occurred');
                    return

                }

            });


        });
        rl.close();

    });

}
else {
    console.log('No write operation');

}

so, when user executes it like node index.js write, it will ask the fileName


Solution

  • you need to refactor your code into methods to show intent properly:

    1. Check if file exists
        function ifFileExists(filepath) {
            try {
                fs.accessSync(filepath, fs.constants.F_OK);
                return true;
            } catch (e) {
                return false;
            }
        }
    
    1. Ask for user input
           function askForUserInput(message) {
            rl.question(message, (fileName) => {
                if (ifFileExists(fileName)) {
                    askForUserInput('File already exists, Please provide a new filename:=>');
                } else {
                    writeToFile(fileName);
                    rl.close();
                }
            });
        }
    
    1. write to file
            function writeToFile(fileName) {
            fs.writeFile('fileNameList.txt', fileName, err => {
                if (err) {
                    console.log('Error occured');
                    return;
                }
                fs.writeFile(fileName, 'Hello', err => {
                    if (err) {
                        console.log('Error occured');
                        return
                    }
                });
            });
        }
    
    1. use it
        if (argv._[0] == 'write') {
            askForUserInput('Please provide the filename:=>');
        }
        else {
            console.log('No write operation');
        }
    
    1. your logic to write filenames in fileNameList.txt looks correct. Have a look at this solution and see, to me it looks like since you have file name as entry you can simply write it to the file and when reading from file add to an array

    node.js - how to write an array to file

    and

    node.js: read a text file into an array. (Each line an item in the array.)