convert base64 to file
convert base64 to file

Hi Guy’s Welcome to Proto Coders Point, In this Article let’s learn how to convert base64 string to file in NODEJS. This works for all kinds of file like Image File, Video File or any kind of document like text, pdf, word File etc.

Convert base64 string to file in nodejs

To convert base64 string to file we can make use of File System Module of NodeJS.

File System Module is an NodeJS library that lets you work with system file & perform read write operation with computer files.

Install fs in nodeJS project

npm i fs

import fs to use it

const fs = require('fs');

let’s assume you already have a file in base64 format.

var base64Str = "SGkgR3V5J3MgV2VsY29tZSB0byBQcm90byBDb2RlcnMgUG9pbnQs";

Convert base64 to file

use writeFile function from fs module to convert base64 to file in nodejs with desired file extension.

fs.writeFile("fileName.txt",base64Str,{encoding:'base64'},(error)=>{
        if(error){
            console.log("Error");
        }else{
            console.log("File Created");
        }
});

Complete Code base64 to file in node

const fs = require('fs');
var base64Str = "SGkgR3V5J3MgV2VsY29tZSB0byBQcm90byBDb2RlcnMgUG9pbnQs"

fs.writeFile("fileName.txt",base64Str,{encoding:'base64'},(error)=>{
        if(error){
            console.log("Error");
        }else{
            console.log("File Created");
        }
});
convert base64 to file in nodejs
convert base64 to file in nodejs