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

2019-05-07 14:31发布

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

2条回答
Ridiculous、
2楼-- · 2019-05-07 15:08

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.

查看更多
冷血范
3楼-- · 2019-05-07 15:28

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

查看更多
登录 后发表回答