Skip to content

Instantly share code, notes, and snippets.

@crspiccin
Last active March 16, 2024 21:00
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save crspiccin/790796a68e7178404de4 to your computer and use it in GitHub Desktop.
Save crspiccin/790796a68e7178404de4 to your computer and use it in GitHub Desktop.
Node.js convert an image to Base 64
//http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html
var fs = require('fs');
// function to encode file data to base64 encoded string
function base64_encode(file) {
// read binary data
var bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
// function to create file from base64 encoded string
function base64_decode(base64str, file) {
// create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
var bitmap = new Buffer(base64str, 'base64');
// write buffer to file
fs.writeFileSync(file, bitmap);
console.log('******** File created from base64 encoded string ********');
}
// convert image to base64 encoded string
var base64str = base64_encode('salvarDocumento.png');
console.log(base64str);
// convert base64 string back to image
base64_decode(base64str, 'copy_salvarDocumento.png');
@piyushsullere
Copy link

i am trying this code i will git this error
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be one of type string, Buffer, or URL. Received type object

@tzvc
Copy link

tzvc commented Mar 2, 2020

Why the need to reallocate another buffer?

// function to encode file data to base64 encoded string
function base64_encode(file) {
  // read binary data
  const bitmap = fs.readFileSync(file);
  // convert binary data to base64 encoded string
  return bitmap.toString('base64');
}

@matkoklaic
Copy link

matkoklaic commented Mar 3, 2020

No need to use two steps when you can use just one:
function base64_encode(file) {
const bitmap = fs.readFileSync(file, { encoding: 'base64' });
}

@NishargShah
Copy link

If you have only one option, you can directly specify it

function base64_encode(file) {
    const base64 = fs.readFileSync(file, 'base64');
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment