NodeJS requires ('./path/to/image/image.jpg') as base64
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 to share