NodeJS require('./path/to/image/image.jpg')作为base64 [英] NodeJS require('./path/to/image/image.jpg') as base64

查看:350
本文介绍了NodeJS require('./path/to/image/image.jpg')作为base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法告诉require如果文件名以.jpg结尾,那么它应该返回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...

推荐答案

我担心为什么" ,但这是如何" :

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');

此机制存在一些严重问题:首先,以这种方式加载的每个图像的数据都将保留在内存中,直到您的应用停止(因此对于加载大量图像没有用),并且由于该缓存机制(也适用于require()的常规使用),您只能将图像加载到缓存一次(在图像文件更改后第二次要求图像,仍然会生成第一个(缓存的)版本,除非您手动开始清除模块缓存.

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.

这篇关于NodeJS require('./path/to/image/image.jpg')作为base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆