How to read file content from Discord message attachment

I’m working on a Discord bot and need to extract data from files that users upload as attachments to messages. I found some code online but it’s not working properly.

if (msg.attachments) {
    let fileAttachment = msg.attachments.first();
    fetchFile(fileAttachment.url);
    
    var fileContent = fs.readFileSync(fileAttachment.name);
    jsonData = JSON.parse(fileContent);
}

The problem is that fetchFile() function doesn’t actually exist and I can’t figure out how to properly download the attachment first before reading it. I’ve been searching for solutions but haven’t found a working method yet. Does anyone know the correct way to handle this? I basically need to get the file data from the attachment URL and then parse it as JSON.

axios works great for this if you prefer it over fetch. just handle errors properly since discord attachment urls expire or fail sometimes. i wrap mine in try/catch so the bot doesn’t crash when people upload corrupted json files.

You’re trying to read a local file that doesn’t exist yet. You need to fetch the attachment content from the URL first. I’ve hit this exact issue before - just use fetch or axios to download the file content straight into memory without saving it locally.

Here’s what worked for me:

if (msg.attachments.size > 0) {
    const attachment = msg.attachments.first();
    const response = await fetch(attachment.url);
    const fileContent = await response.text();
    const jsonData = JSON.parse(fileContent);
}

Make sure your function is async and you have node-fetch installed if you’re using an older Node version. This downloads the file content straight into a string variable instead of trying to read from the filesystem. Way more reliable than downloading and saving the file first.