1

I've been struggling too much with this simple problem ... I'm trying the get a picture from an url to post it to a discord webhook.

request.get(options, (res, err, base64Picture)=>{
}).pipe(fs.createWriteStream(filename)).on('close', ()=>{
   upload(fs.readFileSync('./' + filename))
});

This function works as intended but create a useless tmp file. I want to get the base64 string and convert it to a file format, so I try do do that:

request.get(options, (res, err, base64Picture)=>{
   upload(Buffer.from(base64Picture, 'base64'), filename);
})

This one doesn't work at all. I tried to log both buffers and they are indeed different. That's what I don't get. I don't have much experience from nodejs so that might be something simple, but I have a lot of trouble not knowing the data type ...

Hopefully someone might have an answer for me.

Julien
  • 13
  • 2

1 Answers1

0

In the code you posted, base64Picture is most likely a UTF-8 string, which isn't what you want. You want a binary Buffer instead, so set encoding: null on the request options. Then you can call .toString('base64') on the Buffer to convert it into a base64 string.

For example, this worked for me:

const options = {
    url: 'https://i.imgur.com/8m8GoJu.jpg',
    encoding: null // <----- important
};

request.get(options, (res, err, picture) => {
    // now picture is a Buffer
    const base64String = picture.toString('base64');

    // use base64String as desired...
    // upload(base64String, filename);
});
mamacdon
  • 2,899
  • 2
  • 16
  • 16
  • It now works if I add the "encoding: null" and remove the "Buffer.from" function from my code. Thank you ! For full code reference: https://github.com/ShameSetsu/PixivToDiscordWebhook – Julien Mar 15 '18 at 18:39