Created
April 26, 2018 11:54
-
-
Save tonis2/324746c33d18120f54364ad652d7bde6 to your computer and use it in GitHub Desktop.
Replace data:image urls in JSON
This file contains hidden or 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
import fs from "fs"; | |
import uuid from "uuid/v1"; | |
const replaceDataImg = (string) => { | |
const data = string.replace(/^data:image\/\w+;base64,/, ""); | |
const buf = new Buffer(data, 'base64'); | |
const name = `server/files/${uuid()}.png`; | |
fs.writeFile(name, buf, (error) => { if(error) console.log("Error!", error)}); | |
return `"${name}"`; | |
} | |
const replaceImagesInHTML = (html) => { | |
const regex = /"data:image\/([a-zA-Z]*);base64,([^\"]*)\"/g; | |
const images = html.match(regex); | |
images.forEach(img => { | |
const newImg = replaceDataImg(JSON.parse(img)); | |
html = html.replace(img, newImg); | |
}); | |
return html; | |
} | |
export {replaceImagesInHTML} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use this to send HTML json with data:image as
tags src-es then in backend i replace the data:image with real .png image file location.
And boom you can load the HTML and it contains
tags with file urls instead.