Skip to content

Instantly share code, notes, and snippets.

@sid24rane
Created July 26, 2016 14:26
Show Gist options
  • Save sid24rane/bdf557cf9f835181a994439da0b5b82a to your computer and use it in GitHub Desktop.
Save sid24rane/bdf557cf9f835181a994439da0b5b82a to your computer and use it in GitHub Desktop.
Node.js Base64 Encode Decode -> Image
var buffer = require('buffer');
var path = require('path');
var fs = require('fs');
function encode_base64(filename){
fs.readFile(path.join(__dirname,'/public/',filename),function(error,data){
if(error){
throw error;
}else{
var buf = Buffer.from(data);
var base64 = buf.toString('base64');
//console.log('Base64 of ddr.jpg :' + base64);
return base64;
}
});
}
function decode_base64(base64str , filename){
var buf = Buffer.from(base64str,'base64');
fs.writeFile(path.join(__dirname,'/public/',filename), buf, function(error){
if(error){
throw error;
}else{
console.log('File created from base64 string!');
return true;
}
});
}
encode_base64('ddr.jpg');
decode_base64('any_base64_string_goes_here','rane.jpg');
@christoffdimitar
Copy link

it works. perhaps adding some error checking would make it better

@diegoazh
Copy link

diegoazh commented Aug 7, 2018

Hello, I sugest the following modifications:

'use strict';
// node v8.11.3
const Buffer = require('buffer').Buffer;
const path = require('path');
const fs = require('fs');

/**
 * @param  {string} filename
 */
function encode_base64(filename) {
  fs.readFile(path.join(__dirname, '/public/', filename), function(error, data) {
    if (error) {
      throw error;
    } else {
      let buf = Buffer.from(data);
      let base64 = buf.toString('base64');
      // console.log('Base64 ' + filename + ': ' + base64);
      return base64;
    }
  });
}
/**
 * @param  {string} base64str
 * @param  {string} filename
 */
function decode_base64(base64str, filename) {
  let buf = Buffer.from(base64str, 'base64');

  fs.writeFile(path.join(__dirname, '/public/', filename), buf, function(error) {
    if (error) {
      throw error;
    } else {
      console.log('File created from base64 string!');
      return true;
    }
  });
}

encode_base64('ddr.jpg');
decode_base64('any_base64_string_goes_here', 'rane.jpg');

@kishan12yadav
Copy link

bhai save kaise hoga broo database me

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