Skip to content

Instantly share code, notes, and snippets.

@peterforgacs
Last active February 10, 2018 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterforgacs/1590a9f819111c0de196c132ed533c78 to your computer and use it in GitHub Desktop.
Save peterforgacs/1590a9f819111c0de196c132ed533c78 to your computer and use it in GitHub Desktop.
[base64 string to image file] How to write an image in node.js #Node.js
'use strict';
const util = require('util');
const fs = require('fs');
const write = util.promisify(fs.writeFile);
module.exports = ({ image, identifier, directory }) => {
try {
const extension = image.split(';')[0].match(/jpeg|png|gif/)[0];
const data = image.replace(/^data:image\/\w+;base64,/, '');
const encoding = 'base64';
const file = `${identifier}.${extension}`;
const path = path.join(directory, file);
await writeFile(path, data, encoding);
return path;
} catch (error){
console.error(error);
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment