Convert Image File to Base64 String in Node Js Tutorial

Share this Article
Reading Time: 4 minutes
192 Views

Inside this article we will see the concept of converting an image file to base64 string in node js. If you are looking an article which gives the the idea of image conversion into a base64 encoded string then this article is best for you.

Tutorial will be step by step easy process. Covert image into a base64 encoded string in this node js article will not use any third party npm packages. We will do using a very simple process.

Node JS is an environment where we can deploy and execute javascript based applications. In this article we will covert an image into base64 string using node js.

Learn More –

Let’s get started.


Node Js Application Setup

Please make sure you have node and npm both installed. To check available versions use these commands.

To check node version

$ node -v

To check npm version

$ npm -v

Create a folder with any name say readimage. Open this folder into terminal or command prompt.

Next, we need package.json file. Run this given command into terminal

$ npm init -y

The given command will auto generate package.json file with default values.

Next we need to create a file say server.js into node application.


Application Example Image

We will take an example image inside node application say nodejs-logo.png. You can use any of your own image.


Image Conversion Code

Open server.js file and write this following code into it.

const fs = require('fs');

var base64str = base64_encode('nodejs-logo.png');
console.log(base64str);

// Helper function
function base64_encode(file) {
    return "data:image/gif;base64," + fs.readFileSync(file, 'base64');
}

Application Testing

Open project terminal and type this command.

$ node server.js

We hope this article helped you to learn How To Read and Write Json File in Node Js Tutorial in a very detailed way.

Buy Me a Coffee

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.