【问题标题】:How can I check if a file exists or not to delete it and create it?如何检查文件是否存在以删除并创建它?
【发布时间】:2022-01-27 18:06:47
【问题描述】:

您好,我有一个错误,因为它找不到文件但我不明白,如果有人可以帮助我 =)

if (choice == "txt") {
            const dataWhitelist = await whitelists.find({ 'guildId': interaction.guild.id });
            const nameFile = interaction.guild.id + '.txt';
            if (fs.existsSync(`./tmp/${nameFile}`)) {
                fs.unlinkSync(`./tmp/${nameFile}`)
            }
            for (const i in dataWhitelist) {
                fs.appendFile(`./tmp/${nameFile}`, dataWhitelist[i].userId + ',' + dataWhitelist[i].address + ';', function (err) {
                    if (err) {
                        console.log(err)
                    } else {
                        // done
                    }
                })
            }
            interaction.deferReply({ ephemeral: true });
            interaction.followUp({ content: `Here is the export for your server.`, files: [{ attachment: `./tmp/${nameFile}` }] });
        }

这是我发出命令时遇到的错误

node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[Error: ENOENT: no such file or directory, stat '/home/user/bots/whitelister_mongoose/tmp/859055688965816320.txt'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'stat',
  path: '/home/user/bots/whitelister_mongoose/tmp/859055688965816320.txt'
}

【问题讨论】:

  • 并行多次附加到同一个文件可能不是一个好主意。虽然确切的错误是特殊的,但我不排除这样做是操作系统的奇怪边缘情况行为。使用appendFileSync 或(更好)将整个函数重写为异步。
  • 你有想法将其切换为异步吗? @CherryDT
  • 你似乎已经有了一个异步函数,所以你只需要使用await fs.promises.<whatever>而不是fs.<whatever>Sync(也使用await fs.promises.appendFile)。特殊情况只是 exists 没有承诺版本(您必须改用 stat 并捕获它的错误)但为此可能更容易根本不检查是否存在而只是捕获并忽略unlink 可能抛出的错误,如果它是 ENOENT。

标签: javascript node.js discord.js


【解决方案1】:

同意 CherryDT 的观点,你得到的错误可能是由于多次并行追加到同一个文件。你可以试试下面的异步版本:

if (choice == "txt") {
  const dataWhitelist = await whitelists.find({ 'guildId': interaction.guild.id });
  const nameFile = interaction.guild.id + '.txt';
  try {
    await fs.promises.unlink(`./tmp/${nameFile}`);
    for await (const i in dataWhitelist) {
      await fs.promises.appendFile(`./tmp/${nameFile}`, dataWhitelist[i].userId + ',' + dataWhitelist[i].address + ';');
    }
  } catch(err) {
    console.log(err);
  }
  interaction.deferReply({ ephemeral: true });
  interaction.followUp({ content: `Here is the export for your server.`, files: [{ attachment: `./tmp/${nameFile}` }] });
}

【讨论】:

    猜你喜欢
    • 2011-07-30
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多