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

左心房为你撑大大i 提交于 2019-12-07 08:19:01

问题


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")



来源:https://stackoverflow.com/questions/31241734/nodejs-require-path-to-image-image-jpg-as-base64

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!