Created
July 26, 2016 14:26
-
-
Save sid24rane/bdf557cf9f835181a994439da0b5b82a to your computer and use it in GitHub Desktop.
Node.js Base64 Encode Decode -> Image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
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');
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
it works. perhaps adding some error checking would make it better