117

I'm trying to read an image from client side encoded in base64. How to read with nodejs?

My code:

// add to buffer base64 image
var encondedImage = new Buffer(image.name, 'base64');

fs.readFile(encondedImage, "base64", function(err, buffer){
    if ( err ) {
        console.log('In read file')
        console.log(err)
    } else {
        // check err
        lwip.open(buffer, 'jpg', function(err, image){
            console.log('in open')
            if ( err ) console.log(err)

            if ( image ) console.log(image)
            // check 'err'. use 'image'.
            // image.resize(...), etc.
        });
    }
})

But, I got this error:

In read file
[Error: Path must be a string without null bytes.]
brunocascio
  • 1,867
  • 3
  • 14
  • 21
  • 1
    `fs.readFile` takes a string as its first argument. You're trying to pass it a `Buffer`. – cbr Mar 03 '15 at 14:59

4 Answers4

217

Latest and greatest way to do this:

Node supports file and buffer operations with the base64 encoding:

const fs = require('fs');
const contents = fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});

Or using the new promises API:

const fs = require('fs').promises;
const contents = await fs.readFile('/path/to/file.jpg', {encoding: 'base64'});
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Mike Martin
  • 3,850
  • 1
  • 15
  • 18
  • 3
    `fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'})` does not decode the binary... it's equivalent to `fs.readFileSync('/path/to/file.jpg', 'utf8')` we're merely passing an encoding argument to get a string instead of a buffer – Ray Foss Mar 16 '22 at 16:57
133

I think that the following example demonstrates what you need: I removed the link because it was broken.

The essence of the article is this code part:

var fs = require('fs');

// function to encode file data to base64 encoded string
function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');
}

// function to create file from base64 encoded string
function base64_decode(base64str, file) {
    // create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
    var bitmap = new Buffer(base64str, 'base64');
    // write buffer to file
    fs.writeFileSync(file, bitmap);
    console.log('******** File created from base64 encoded string ********');
}

// convert image to base64 encoded string
var base64str = base64_encode('kitten.jpg');
console.log(base64str);
// convert base64 string back to image 
base64_decode(base64str, 'copy.jpg');
Sjoerd
  • 1,724
  • 2
  • 13
  • 13
  • I got buffer is undefined error. I am missing some js library or something else – Krishna Aug 19 '16 at 13:16
  • @Krishnavrinsoft: You need to have node.js installed. https://nodejs.org – Sjoerd Aug 20 '16 at 14:15
  • 6
    If the goal is to create a base64-encoded [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) the solution falls a bit short. The actual data is correct, but the string is missing the `data:[][;base64],` prefix. – Marty Chang Oct 07 '16 at 14:03
  • You are right I think, but that was not part of the question for as far as I have understood it. – Sjoerd Mar 09 '17 at 13:31
  • 9
    `new Buffer` is redundant. `fs.readFileSync` returns buffer if encoding is not specified. You can just do `fs.readFileSync([..]).toString('BASE64')`. – Gajus Aug 25 '17 at 18:47
  • 1
    @Gajus You can even go farther. readFileSync now can do the encoding for you. Just do `fs.readFileSync('...', { encoding: 'BASE64' })` – Mike Martin Jan 09 '19 at 23:01
  • the link seems broken! – Ebrahim Nov 12 '21 at 14:00
  • It helps A LOT! `function base64_encode(file) { var bitmap = fs.readFileSync(file); return new Buffer(bitmap).toString('base64'); }` Thank you! – Igor Kurkov May 28 '22 at 11:39
  • downvoting for converting buffer to buffer `new Buffer()` can be removed – mikep May 29 '23 at 11:49
10
var fs = require('fs');

function base64Encode(file) {
    var body = fs.readFileSync(file);
    return body.toString('base64');
}


var base64String = base64Encode('test.jpg');
console.log(base64String);
2

The following code reads a text file. Then converts it to text, then reads it as base64 and puts that into a binary buffer, and saves it back to a true binary.

import { readFileSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
const contents = readFileSync('./temp.txt')
const buffedInput = Buffer.from(contents.toString(), 'base64')
writeFileSync(`${tmpdir}/temp.zip`, buffedInput)
Ray Foss
  • 3,649
  • 3
  • 30
  • 31