nodejs save base64 image to file code example

Example 1: convert file into base64 in javascript

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file).then(
  data => console.log(data)
);

Example 2: nodejs read image as base64

const fs = require('fs');
const contents = fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});

Example 3: nodejs fs writefile base64url

const fileContents = new Buffer(attachmentResponse.data.data, 'base64')
fs.writeFile(part.filename, fileContents, (err) => {
  if (err) return console.error(err)
  console.log('file saved to ', part.filename)
})

Example 4: png to base64 javascript

function toDataURL(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      callback(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}

toDataURL('https://cdn.discordapp.com/attachments/571092147801948204/784586541146177606/6f32c864-985a-481d-8d8e-bd1f14ab9951.png', function(dataUrl) {
  console.log('RESULT:', dataUrl)
})

Example 5: nodejs read image as base64

const fs = require('fs').promises;
const contents = await fs.readFile('/path/to/file.jpg', {encoding: 'base64'});