【问题标题】:My random image bot tries to pull images from the main folder instead of the specified folder我的随机图像机器人尝试从主文件夹而不是指定文件夹中提取图像
【发布时间】:2021-01-31 14:15:26
【问题描述】:

我已经尝试了几次以使其工作,但无法弄清楚如何将机器人引导到正确的文件夹。

运行命令时总是出现这个错误

(node:15532) UnhandledPromiseRejectionWarning: E​​rror: ENOENT: no such file or directory, stat 'c:\Users\Owner\Desktop\Discordbot\93c5b877d8afcf7a9590fcb149e849c53c6cc1ed.jpg'

有谁知道我做错了什么以及如何解决它?

const { Client, MessageAttachment } = require('discord.js');
var fs = require('fs');
var files = fs.readdirSync('./pics/'); // I thought this would direct it to where it neeeds to be

module.exports = {
    execute(message, args){
   var item = files[Math.floor(Math.random() * files.length)];
   var item = new MessageAttachment(item);
   message.channel.send(item)
    }
}

请帮忙。

【问题讨论】:

  • 文件夹“pics”是主根文件夹还是子文件夹?
  • 与index.js和package.json在同一个文件夹

标签: node.js discord discord.js


【解决方案1】:

我会建议你使用绝对路径。

  1. 您可以使用__dirname 指向当前文件的目录。

    var files = fs.readdirSync(path.join(__dirname, 'pics'));

  2. 您可以使用require.main.filename 指向放置package.json 的目录(主目录)

    var appDir = path.dirname(require.main.filename); var files = fs.readdirSync(path.join(appDir, 'pics'));

【讨论】:

  • var files = fs.readdirSync(path.join(__dirname, 'pics'));
  • 我这样做了,它将进入我的命令文件夹而不是主文件夹。我该如何预防?
  • @AsukaSZN 我已经根据您的评论更新了我的答案
  • 我明白了。 pics 应该保留为 'pics' 还是 ''/pics/'?
  • @AsukaSZN path.join 将处理斜线。只需使用“图片”
猜你喜欢
  • 2012-05-02
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 2020-01-07
  • 1970-01-01
  • 2012-06-13
相关资源
最近更新 更多