NodeJS需要('./path / to / image / image.jpg')作为base64

问题描述 投票:4回答:2

有没有办法告诉require,如果文件名以.jpg结尾,那么它应该返回它的base64编码版本?

var image = require('./logo.jpg');
console.log(image); // data:image/jpg;base64,/9j/4AAQSkZJRgABAgA...
node.js require
2个回答
6
投票

我担心“为什么”,但这里是“如何”:

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()),你只能将图像加载到缓存中一次(在文件发生变化后第二次需要图像,仍会产生第一个缓存版本,除非你手动开始清理模块高速缓存)。

换句话说:你真的不想要这个。


1
投票

你可以使用fs.createReadStream("/path/to/file")

© www.soinside.com 2019 - 2024. All rights reserved.