javascriptnode.jsnode-fetch

SyntaxError: Unexpected identifier for "fetch"


I was making a discord bot using NodeJS, and everytime i go boot up the bot it shows this error:

headers = (await fetch(filtered.fileUrl, { method: 'HEAD' })).headers
                 ^^^^^
SyntaxError: Unexpected identifier

What i knew is that, fetch requires node-fetch. At first, i thought the problem was that i was using node-fetch@3.0.0, which doesn't support const fetch = require('node-fetch') but even when i downgraded it to node-fetch@2.6.1 this exact issue still persists.

Full code:

const fetch = require('node-fetch')
const Booru = require('booru')
const Discord = require('discord.js')
const { escapeMarkdown } = Discord.Util
const path = require('path')
const Color = `RANDOM`;
    module.exports = {
      info: {
        name: "booru",
        description: "booru image scraper",
        cooldown: 30,
      },
      async execute(client, message, args, Discord) {
        const tag_query = args.join(' ');

        if (!message.content.includes('help')) {
          if (!message.content.includes('something')) {
            const hornyEmbed = new Discord.MessageEmbed()
              .setTitle('embed cut to preserve space')
            if (!message.channel.nsfw) return message.channel.send(hornyEmbed)

            Booru.search('gelbooru', tag_query, {
                limit: 1,
                random: true
              })
              .then(posts => {
                const filtered = posts.blacklist(['blacklist, of course.'])
                if (filtered.length === 0) {
                  const notfoundEmbed = new Discord.MessageEmbed()
                    .setDescription("embed cut to preserve space")
                  message.channel.send(notfoundEmbed)
                }

                let tags =
                  filtered.tags.join(', ').length < 50 
                  ? Discord.Util.escapeMarkdown(filtered.tags.join(', ')) 
                  : Discord.Util.escapeMarkdown(filtered.tags.join(', ').substr(0, 50)) 
                  + `... [See All](https://giraffeduck.com/api/echo/?w=${Discord.Util
                                            .escapeMarkdown(filtered.tags.join(',').replace(/(%20)/g, '_'))
                                            .replace(/([()])/g, '\\$1')
                                            .substring(0, 1200)})`

                let headers
                let tooBig = false
                let imgError = false

                try {
                  headers = (await fetch(filtered.fileUrl, {
                    method: 'HEAD'
                  })).headers
                } catch (e) {
                  imgError = true
                }

                if (headers) {
                  tooBig = parseInt(headers.get('content-length'), 10) / 1000000 > 10
                }

                for (let post of posts) {

                  embed_nsfw = new Discord.MessageEmbed()
                    .setTitle('you horny')
                    .setColor('#FFC0CB')
                    .setAuthor('-')
                    .setDescription(`-` +
                      `**Provided by:** Gelbooru.com | `, +`[**Booru Page**](${filtered.postView}) | ` +
                      `**Rating:** ${filtered.rating.toUpperCase()} | ` +
                      `**File:** ${path.extname(filtered.file_url).toLowerCase()}, ${headers ? fileSizeSI(headers.get('content-length')) : '? kB'}\n` +
                      `**Tags:** ${tags}` +
                      (!['.jpg', '.jpeg', '.png', '.gif'].includes(
                          path.extname(filtered.fileURL).toLowerCase(),
                        ) ?
                        '`The file will probably not embed.`' :
                        '') +
                      (tooBig ? '\n`The image is over 10MB and will not embed.`' : '') +
                      (imgError ? '\n`I got an error while trying to get the image.`' : ''),
                    )
                    .setImage(filtered.sampleUrl)
                  message.channel.send(embed_nsfw);
                }
              })
          }
          if (message.content.includes('something')) {
            const helpEmbed = new Discord.MessageEmbed()
              .setTitle('cut to preserver space')
            message.channel.send(helpEmbed)
          }
        }
        if (message.content.includes('help')) {
          const helpEmbed = new Discord.MessageEmbed()
            .setTitle('cut to preserver space')
          message.channel.send(helpEmbed)
        }
      }
    }

I know this code is extremely messy, because it's basically a frankenstein's code put together from different codes i found. So aside from the solution for the main topic, a pointer on another issue i hadn't noticed will also be appreciated.

NodeJS version 16.13.0, NPM version 8.1.0, DiscordJS version 12.5.3, Running on a Heroku server.


Solution

  • try add async to .then(posts => .

    Booru.search('gelbooru', tag_query, {
    ...
      .then(async posts => {
        const filtered = posts.blacklist(['blacklist, of course.'])
        if (filtered.length === 0) {
          const notfoundEmbed = new Discord.MessageEmbed()
          .setDescription("embed cut to preserve space")
          message.channel.send(notfoundEmbed)
        }
    ...
    
      try {
        headers = (await fetch(filtered.fileUrl, {
          method: 'HEAD'
        })).headers
      }