Why can repl.it not load a default font config?

491 Views Asked by At

Info: Using NodeJS, Discord.js, and canvas in this file, along with repl.it hosting.

This code worked on my local machine, but upon moving to repl.it to host it, I got the error "Fontconfig error: Cannot load default config file" Code below

const Canvas = require('canvas')
const { MessageAttachment } = require('discord.js')
const path = require('path')

module.exports = (client) => {
  client.on('guildMemberAdd', async (member) => {
    const { guild } = member

    const channelId = "830958927674998815"
    if (!channelId) {
      return
    }

    const channel = guild.channels.cache.get(channelId)
    if (!channel) {
      return
    }

    const canvas = Canvas.createCanvas(700, 250)
    const ctx = canvas.getContext('2d')

    const background = await Canvas.loadImage(
      path.join(__dirname, '../background.png')
    )
    let x = 0
    let y = 0
    ctx.drawImage(background, x, y)

    const pfp = await Canvas.loadImage(
      member.user.displayAvatarURL({
        format: 'png',
      })
    )
    x = canvas.width / 2 - pfp.width / 2
    y = 25
    ctx.drawImage(pfp, x, y)

    ctx.fillStyle = '#ffffff'
    ctx.font = '35px sans-serif'
    let text = `Welcome ${member.user.tag}`
    x = canvas.width / 2 - ctx.measureText(text).width / 2
    ctx.fillText(text, x, 60 + pfp.height)

    ctx.font = '30px sans-serif'
    text = `Member #${guild.memberCount}`
    x = canvas.width / 2 - ctx.measureText(text).width / 2
    ctx.fillText(text, x, 100 + pfp.height)

    const attachment = new MessageAttachment(canvas.toBuffer())
    channel.send('', attachment)
  })
}```
1

There are 1 best solutions below

0
On

You need to set a fontconfig directory for libfontconfig to reference, along with fonts.

I️ just went through this same thing, but on AWS Lambda. What I️ got working was creating a file called font.conf containing:

<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
  <dir>/path/to/fonts</dir>
  <cachedir>/tmp/fonts-cache</cachedir>
  <config></config>
</fontconfig>
<match target="pattern">
  <test qual="any" name="family">
          <string>your-font-name</string>
  </test>
  <edit name="family" mode="assign" binding="same">
          <string>your-font-name</string>
  </edit>
</match>

With this and a folder containing your fonts set, you need to set the FONTCONFIG_PATH env variable. Like this:

process.env.FONTCONFIG_PATH = path/to/font.conf

Make sure that this is done before you call createCanvas.

Hope this helps!