使用 Yargs 的 Fs 操作

Fs operations with Yargs

我必须用 Yargs.For 示例执行一些操作- 1- 使用 fs 模块写入文件,每次写入操作都需要创建一个新文件, 2-您必须从用户那里获取 i/p 作为文件名,并将文件名保存在一个数组中(数组部分未完成),在一个单独的文本文件中 3-下次当用户输入相同的文件名时,如果存在则再次要求提供新的文件名,然后与第 1 点相同。 我面临第 2 点的问题,如何在文本文件中写入数组,以及如果用户继续提供现有文件名如何再次调用 'Please provide the fileName'。

到目前为止我已经这样做了-

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');

}

所以,当用户像 node index.js write 那样执行它时,它会询问 fileName

您需要将代码重构为方法以正确显示意图:

  1. 检查文件是否存在
    function ifFileExists(filepath) {
        try {
            fs.accessSync(filepath, fs.constants.F_OK);
            return true;
        } catch (e) {
            return false;
        }
    }
  1. 要求用户输入
       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. 写入文件
        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. 使用它
    if (argv._[0] == 'write') {
        askForUserInput('Please provide the filename:=>');
    }
    else {
        console.log('No write operation');
    }
  1. 你在 fileNameList.txt 中写入文件名的逻辑看起来是正确的。 看看这个解决方案,在我看来,因为你有文件名作为条目,你可以简单地将它写入文件,并在从文件读取时添加到数组

node.js - how to write an array to file

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

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");
}