I was recently working on an internal project and needed to convert some Scalable Vector Graphics (SVG) images to Base64 encoded strings. The files were very small (< 500 bytes). This particular application required all HTML content to be "inlined". Whatever your reason for showing up on my doorstep, this post describes how to convert data in a file to and from Base64 using Node.js.

Note: This is meant to be a simple utility that I can use as needed. This is not a production ready piece of code and it includes no error checking whatsoever. I am also assuming that you already have Node.js installed and that everything is working properly on your system.

Base64 Encode Text Data

Step 1: Create a new JavaScript program and call it whatever you want. I called mine svg2base64.js because that is what I am using it for. Then, enter the following code into your source file.

var fs   = require('fs'),  
    file = process.argv[2],
    data = fs.readFileSync(file);

console.log(data.toString('base64'));

Step 2: Run the program and provide the file name parameter to generate a Base64 encoded string of that file's contents. The program will read the contents of a file identified by argv[2] and output that content as a Base64 encoded string.

jbiard$ node svg2base64.js 48x48.svg 

NB: My source file was XML-based. I did not test this program against binary data so you may need to alter the program to suite your own needs if you run into issues, although it should work. Assuming you fed this program a tiny data file (< 500 bytes), then you will get output similar to the following:

PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Inllcy
I/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iNDgi
IGhlaWdodD0iNDgiIHZpZXdCb3g9IjAgMCA0OCA0OCIgcHJlc2VydmVBc3BlY3RSYXRpbz
0ibm9uZSI+PGRlZnM+PHN0eWxlIHR5cGU9InRleHQvY3NzIj48IVtDREFUQVsjYXZhdGFy
XzEyM0FCQyB0ZXh0IHsgZmlsbDojQUFBQUFBO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1mYW
1pbHk6QXJpYWwsIEhlbHZldGljYSwgT3BlbiBTYW5zLCBzYW5zLXNlcmlmLCBtb25vc3Bh
Y2U7Zm9udC1zaXplOjhwdCB9IF1dPjwvc3R5bGU+PC9kZWZzPjxnIGlkPSJhdmF0YXJfMT
IzQUJDIj48cmVjdCB3aWR0aD0iNDgiIGhlaWdodD0iNDgiIGZpbGw9IiNFRUVFRUUiLz48
Zz48dGV4dCB4PSI2IiB5PSIyOCI+ZFsqXypdYjwvdGV4dD48L2c+PC9nPjwvc3ZnPg==

This program is very simple and as noted before, contains absolutely no error checking. If you are at all concerned about it then you should add any error checking code as needed.

The magic here is happening using an instance of the Node.js Buffer class. Buffers have several methods for converting streams of data to various encodings. For more details, check out the documentation.

Base64 Decode Text Data

It turns out going the other direction is not so bad. It does require a little more code. The next program we write will read a file that contains Base64 encoded data and output the data as text (ascii) to the console. Follow the same steps as before to create a script and run the program. (I called mine base64toSVG.js because that is what I used it for.)

var fs   = require('fs'),  
    file = process.argv[2],
    data = fs.readFileSync(file);

console.log(new Buffer(data.toString(), 'base64').toString('ascii'));

I stored the Base64 encoded SVG in a file called svg.base64 and then I ran this new program as follows.

jbiard$ node base64toSVG.js svg.base64 

The program reads the data from the file provided (svg.base64) and then converts that to a string. The final step uses the toString('encoding') function of the Buffer class to convert the data back to ASCII.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48" preserveAspectRatio="none">
    <defs>
        <style type="text/css">
            <![CDATA[#avatar_123ABC text { fill:#AAAAAA;font-weight:bold;font-family:Arial, Helvetica, Open Sans, sans-serif, monospace;font-size:8pt } ]]>
        </style>
    </defs>
    <g id="avatar_123ABC">
        <rect width="48" height="48" fill="#EEEEEE"/>
        <g>
            <text x="6" y="28">d[*_*]b</text>
        </g>
    </g>
</svg>

NB: If your original file did not contain text data then this probably won't work for you. If your source file was binary for example, you will need to alter this program to work for your own use-case.

SVG

Cheers!