Last active
February 10, 2018 19:32
-
-
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
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
'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