peterforgacs
2/10/2018 - 7:28 PM

[base64 string to image file] How to write an image in node.js #Node.js

[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;
    }
}