NodeJS requires ('./path/to/image/image.jpg') as base64

Is there a way to say require

that if the filename ends with .jpg

then it should return its base64 encoded version?

var image = require('./logo.jpg');
console.log(image); // data:image/jpg;base64,/9j/4AAQSkZJRgABAgA...

      

+3


source to share


2 answers


I'm worried about the "why", but here's the "how":

var Module = require('module');
var fs     = require('fs');

Module._extensions['.jpg'] = function(module, fn) {
  var base64 = fs.readFileSync(fn).toString('base64');
  module._compile('module.exports="data:image/jpg;base64,' + base64 + '"', fn);
};

var image = require('./logo.jpg');

      



There are some serious problems with this mechanism: firstly, the data for each image loaded in this way will be kept in memory until your application stops (so it's not useful for loading a lot of images), and from- behind this caching mechanism (which also applies to regular use require()

), you can only load one image into the cache once (by requiring the image a second time after changing it, the first cached version will still be issued if you only manually run the module cache cleanup) ...

In other words: you really don't want this.

+5


source


you can use fs.createReadStream("/path/to/file")



+1


source







All Articles