In this post, I will share how to embed an image data directly into the document with data URI scheme in Node.js and Jade. That process will basically require conversion of an image into base64 format.

This is an example of a small red dot image embedded in HTML:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

The data URI scheme format is as follows:

data:[<MIME-type>][;charset=<encoding>][;base64],<data>

Images represented in data URI scheme are basically a long strings encoded in base64 format which are interpreted by a browser as a type of a file we are saying it is (<MIME-type>).

Node.js and Jade Example

I am going to use default express web application framework with Jade templating engine.

In order to install express run the following commands:

npm install express

To generate default express application you can use a command provided by express module:

node node_modules/.bin/express

Terminal output would be like:

Terminal

Note that you will also need to install all required modules which were added to package.json file during the application creation. You can do that by calling:

npm install

I will add a few modification:

  • Embed image using data URI scheme into the index Jade template (note that Jade code does not look like HTML markup)
  • Add code converting an image in base64 format to a request handler method.

I am going to use Wikipedia Logo image as an embed image:

Wikipedia Logo

Jade template used for rendering is as follows:

extends layout

block content
  h1= title
  p Welcome to #{title}
  img(alt='Wikipedia', src='data:img/png;base64,#{src}')

Note that the layout page generated by express does not need any modifications.

The request handler method look like:

var fs = require('fs')
    , path = require('path');

exports.index = function(req, res){
    fs.readFile(
        path.join(__dirname, '../wikipedia.png'),
        function (err, data) {
            res.render('index', {
                title: 'Express',
                src: data.toString('base64')
            });
    })
};

In order to use power of Node.js I used asynchronous function (fs.readFile()) to read the file content. Once the file data is ready, index template is rendered, and the image source converted in base64 format is passed as a parameter.

Rendered page looks like:

Embedded Image

Why would you do this?

One of the main advantages is to save HTTP requests in order to improve page load time. However, the mechanism has also its disadvantages.

Conclusion

In this post I just wanted to focus on an easy way of converting an image into base64 format and then embedding the image data directly into the document with data URI scheme. Decision if the approach will be of any use in your project is a different matter. I would recommend going through advantages and disadvantages, before you make any decisions.

Enjoy!