Convert any Image blob field to file using Mysql and NodeJs

Ricardo Arbois Jr.
1 min readSep 12, 2021

This code sample will convert any database blob to real file and save directly to your drive, this covers the example using Mysql database and Nodejs.

Installing Package:

npm install cli-progress — save

npm install fs — save

npm install sync-mysql — save

Setup the required package.

const fs = require(‘fs’);

const Mysql = require(‘sync-mysql’);

const cliProgress = require(‘cli-progress’);

Setup the Mysql connection

const connection = new Mysql({

host:’localhost’,

user:’root’,

password:’12345',

database: ‘DbBlob’

})

Setting up the getData function to fetch the blob field in the database.

async function getData() {

// create a new progress bar instance and use shades_classic theme

const bar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);

var sql = “select photodesc, photo from imagestorage where mimedata in

(‘image/jpg’,’image/jpeg’,’image/gif’,’image/png’,’image/bmp’,’image/tiff’) order

by mimedata asc”;

var result = await connection.query(sql)

console.log(‘Total Record: ‘+result.length)

bar.start(result.length, 0, {

speed: “125”

});

var cnt = 1;

result.forEach((row) => {

setTimeout(() => {

convertToFile(row);

}, 1000);

bar.update(cnt);

cnt++;

});

// stop the progress bar

bar.stop();

console.log(‘Uploading complete: ‘+result.length)

//process.exit()

}

In this section will convert the binary blob to file

function convertToFile(row){

var base64Image = Buffer.from( row[‘photo’], ‘binary’ ).toString(‘base64’);

fs.writeFile(row[‘photo_desc’],base64Image, {encoding: ‘base64’}, function(err) {

console.log(‘File created’);

});

}

Call the function here…

getData() //call the function

There you go….

You can use this code without any risk, feel free to try and let me know your feedback .

Thank you!

--

--

Ricardo Arbois Jr.

Fullstack Developer, AI , System Developer,System Engineer, Living a simple life and love too code.