0

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

sunny
  • 85
  • 1
  • 1
  • 6

2 Answers2

1

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.)

0
const argv = require("yargs").argv;
const fs = require("fs");
const readline = require("readline");

function ifFileExists(fileName) {
  return new Promise((resolve, reject) => {
    fs.readFile("array.txt", function (err, arrayData) {
      if (err) {
        if (err.code === "ENOENT") {
          handleWhenArrayFileNotFound(reject, resolve);
        } else {
          reject("file read error");
        }
      }

      if (arrayData) {
        handleWhenArrayExists(arrayData, resolve, fileName);
      }
    });
  });

  function handleWhenArrayFileNotFound(reject, resolve) {
    let content = fileName;
    content += "\n";
    fs.writeFile("array.txt", content, (error) => {
      if (error) {
        console.log("Error occured");
        reject("file write error");
      }
      rl.close();
      resolve("created");
    });
  }

  function handleWhenArrayExists(arrayData, resolve, fileName) {
    if (fileNamePresentInArray(arrayData, fileName)) {
      askForNewName("File already exists, Please provide a new filename:=>");
    } else {
      resolve("create file");
    }
  }
}

function fileNamePresentInArray(arrayData, fileName) {
  var array = arrayData.toString().split("\n");
  return array.includes(fileName);
}

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

function askForNewName(message) {
  rl.question(message, (fileName) => {
    fs.readFile("array.txt", function (err, arrayData) {
      if (err) {
        console.log("array.txt not found");
      }
      if (arrayData) {
        if (fileNamePresentInArray(arrayData, fileName)) {
          askForNewName(
            "File already exists, Please provide a new filename:=>"
          );
        } else {
          writeToFile(fileName);
          rl.close();
        }
      }
    });
  });
}

function askForUserInput(message) {
  rl.question(message, (fileName) => {
    ifFileExists(fileName)
      .then((res) => {
        writeToFile(fileName, res);
      })
      .catch((err) => {
        console.log(err);
      });
  });
}

function writeToFile(fileName, data) {
  if (data !== "created") {
    let content = fileName;
    content += "\n";
    fs.appendFile("array.txt", content, (err) => {
      if (err) console.log(err);
    });
  }

  fs.writeFile(fileName, "You are awesome", (err) => {
    if (err) {
      console.log("Error occured");
    }
  });
}

if (argv._[0] == "write") {
  askForUserInput("Please provide the filename:=>");
} else {
  console.log("No write operation");
}
Safnas
  • 144
  • 1
  • 11