0

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

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

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 一样执行它时,它会询问文件名

4

2 回答 2

1

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

  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 - 如何将数组写入文件

node.js:将文本文件读入数组。(每一行都是数组中的一个项目。)

于 2020-07-21T15:56:45.873 回答
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");
}
于 2022-02-02T17:19:43.760 回答