To save a Base64 string received from a client or API back into its original file format (like .jpg or .pdf ), you must strip the metadata header and write it to the disk using the fs module.
When you need to fetch an image or PDF from a remote server and convert it to Base64 for use in a JSON response or data URI, you can use the Axios HTTP client or the built-in https module.
Use fs.writeFile with the encoding: 'base64' option or by creating a Buffer first. javascript nodejs download base64
Use the global Buffer class to transform the binary data into a string. javascript
const fs = require('fs'); const base64String = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."; const base64Data = base64String.replace(/^data:image\/\w+;base64,/, ""); fs.writeFile('image.png', base64Data, { encoding: 'base64' }, (err) => { if (err) console.log(err); else console.log('File saved successfully!'); }); Use code with caution. Key Considerations www.codeblocq.comhttps://www.codeblocq.com Convert a base64 string to a file in Node - CodeBlocQ To save a Base64 string received from a
Base64 strings often start with a prefix like data:image/png;base64, . This must be removed before decoding.
const axios = require('axios'); async function downloadToBase64(url) { const response = await axios.get(url, { responseType: 'arraybuffer' }); const base64 = Buffer.from(response.data, 'binary').toString('base64'); return `data:${response.headers['content-type']};base64,${base64}`; } Use code with caution. How to Save ("Download") a Base64 String to a File javascript Use the global Buffer class to transform
It is critical to set the response type to arraybuffer or null so the data isn't corrupted by default string encoding.