Skip to content

Instantly share code, notes, and snippets.

@betacar

betacar/image-to-base64.js

Last active Feb 11, 2016
Embed
What would you like to do?
Transform images to base64 strings
const fs = require('fs');
const regex = /(\.|\/)(gif|jpe?g|png|txt)$/i;
const dir = './';
const encoding = 'base64';
fs.readdir(dir, (err, files) => {
if (err) return err;
files.forEach((file) => {
// Skip current file
if (file === __filename.slice(__dirname.length + 1)) return;
fs.readFile(`${dir}${file}`, {encoding}, (err, str) => {
if (err) return err;
const ext = regex.exec(file)[2];
console.log('################################################################################');
console.log(file);
console.log(`data:image/${ext};base64,${str}`);
console.log('################################################################################');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment