NodeJS require('./path/to/image/image.jpg'

2019-05-07 14:40发布

问题:

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...

回答1:

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.



回答2:

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