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
you need to refactor your code into methods to show intent properly:
function ifFileExists(filepath) {
try {
fs.accessSync(filepath, fs.constants.F_OK);
return true;
} catch (e) {
return false;
}
}
function askForUserInput(message) {
rl.question(message, (fileName) => {
if (ifFileExists(fileName)) {
askForUserInput('File already exists, Please provide a new filename:=>');
} else {
writeToFile(fileName);
rl.close();
}
});
}
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
}
});
});
}
if (argv._[0] == 'write') {
askForUserInput('Please provide the filename:=>');
}
else {
console.log('No write operation');
}
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.)