Data URLs are composed of four parts: a prefix (data:
), a MIME type indicating the type of data, an optional base64
token if non-textual, and the data itself:
data:[<mediatype>][;base64],<data>
Now we have this dataurl and we want to convert back to file that can be image, doc , text or anything. We can follow the following approach to achieve.
Step 1.
Get only data part from the dataulr.
data = dataurl.replace(/data:.*base64,/,"");
in dataurl “base64” will be available if data is non-textual like image, ms docx pdf etc. For that you can use
data = dataurl.replace(/data:.*,/,"");
Step 2.
Write a file with extracted data
fs.writeFileSync("Filename.mimetype", data, {encoding:"base64})
Complete Code
let dataurl = <anydataurl> let data = dataurl.replace(/data:.*base64,/,""); fs.writeFileSync("my.png", data, {encoding:"base64})