bAN
bAN

Reputation: 13825

Download a file to a base64 string

I'm running Node.js code on a readonly file system and I would like to download a file and convert this file directly to a base64 string but without writing the file on the disk.

Now I have the following:

let file = fs.createWriteStream(`file.jpg`);
request({
    uri: fileUrl
  })
  .pipe(file).on('finish', () => {
    let buff = fs.readFileSync(file);
    let base64data = buff.toString('base64');
})

But this solution is writing on the disk so this is not possible for me.

I would like to do the same but without the need of the temp file on the disk. Is it possible?

Upvotes: 0

Views: 1148

Answers (1)

jfriend00
jfriend00

Reputation: 707238

You don't pipe() into a variable. You collect the data off the stream into a variable as the data arrives. I think you can do something like this:

const Base64Encode = require('base64-stream').Base64Encode;
const request = require('request');

let base64Data = "";
request({
    uri: fileUrl
}).pipe(new Base64Encode()).on('data', data => {
    base64Data += data;
}).on('finish', () => {
    console.log(base64Data);
}).on('error', err => {
    console.log(err);
});

Upvotes: 1

Related Questions