简体   繁体   中英

Node.js: [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined

I'm trying to make a discord bot that saves images sent to it into a folder, and I'm getting this error:

TypeError: [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined.

This is my code:

const Discord = require("discord.js");
const fs = require("fs");
const client = new Discord.Client();

var prefix = "."

client.on("ready", () => {
  client.user.setStatus('online');
  console.log("Bot is on.")
});

client.on("message", message => {
  console.log(__dirname)
  var image = message.attachments.first()
  fs.writeFileSync(`./${image.name}`, image.file);
})

client.login(process.env.token);

Note: I'm using Discord.js v12.5.3

There is no file property on attachments . There is a url property though from where you can download the image. You can use node-fetch to fetch the file (you'll need to install it by running npm i node-fetch@2 in your command line). Once the file is fetched, you can use fs.writeFileSync() .

The following code works fine:

// using discord.js v12
const { Client } = require('discord.js');
const fetch = require('node-fetch');
const fs = require('fs');

const client = new Client();
const prefix = '.';

client.on('message', async (message) => {
  if (message.author.bot) return;

  const image = message.attachments.first();

  if (!image)
    return console.log('No attached image found');

  // add more if needed
  const imageFiles = ['image/gif', 'image/jpeg', 'image/png', 'image/webp'];

  if (!imageFiles.includes(image.contentType))
    return console.log('Not an image file');

  try {
    const res = await fetch(image.url);
    const buffer = await res.buffer();

    fs.writeFileSync(`./${image.name}`, buffer);
  } catch (error) {
    console.log(`Error reading/writing image file:`, error);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM