【问题标题】:Getting an random image from a folder discord.js从文件夹 discord.js 中获取随机图像
【发布时间】:2021-07-07 17:51:16
【问题描述】:

您好,我正在尝试从文件夹中获取随机图像并让不和谐机器人发送它。当我键入命令时,我收到以下错误: (node:15184) UnhandledPromiseRejectionWarning: E​​rror: ENOENT: no such file or directory, stat 'c:\Users\Charlie\Desktop\discordbot2\t.png'

这是我的代码:

var fs = require('fs');
client.on("message",message=>{
  if(message.content==('image')){
    console.log("image")
    var files = fs.readdirSync('folder')
    var chosenFile = files[Math.floor(Math.random() * files.length)] 
    console.log(chosenFile)
    message.channel.send(
      {
        files : [
          chosenFile
        ]
      }
    )
  }
})

【问题讨论】:

标签: javascript node.js discord.js


【解决方案1】:

files 选项中传递给message.channel.send() 的路径名只是文件名。它应该是一个路径(相对于当前目录或绝对路径),这就是它的解释方式。由于所选文件不在当前目录中,因此会生成 ENOENT "no such file or directory" 错误。

要创建相对路径,您可以使用path.join,同时传递文件所在目录的路径和文件名:

const path = require('path');
...
    message.channel.send({files: [path.join('folder', chosenFile)] })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2020-08-30
    相关资源
    最近更新 更多