Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a way to tell require that if file name ends with .jpg then it should return base64 encoded version of it?

var image = require('./logo.jpg');
console.log(image); // data:image/jpg;base64,/9j/4AAQSkZJRgABAgA...
like image 721
vbarbarosh Avatar asked Feb 09 '23 15:02

vbarbarosh


2 Answers

I worry about the "why", but here is "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's some serious issues with this mechanism: for one, the data for each image that you load this way will be kept in memory until your app stops (so it's not useful for loading lots of images), and because of that caching mechanism (which also applies to regular use of require()), you can only load an image into the cache once (requiring an image a second time, after its file has changed, will still yield the first—cached—version, unless you manually start cleaning the module cache).

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

like image 187
robertklep Avatar answered Feb 12 '23 09:02

robertklep


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

like image 26
KlwntSingh Avatar answered Feb 12 '23 09:02

KlwntSingh