all files / packages/ngdoc-ext/processors/ embedImages.js

33.33% Statements 6/18
0% Branches 0/2
16.67% Functions 1/6
33.33% Lines 6/18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                                                                          
var _ = require('lodash');
var path = require('path');
var mime = require('mime');
var fs = require('fs');
 
/**
 * @dgProcessor embedImages
 * @description
 * Embeds local images to the page
 */
module.exports = function embedImages(log, aliasMap, moduleMap, createDocMessage) {
  return {
    $runBefore: ['writeFilesProcessor'],
    $process: function(docs) {
      _(docs)
        .groupBy('docType')
        .tap(function(docs){
          // TODO: make exclusions configurable
          // do not embed images references in app templates
          delete docs.website;
        })
        .forEach(function(areas) {
          areas.forEach(function(doc) {
            doc.renderedContent = doc.renderedContent.replace(/(<img.+?src=['"])([^"']+)/ig, function (m0, m1, m2) {
              if (/^https?:\/{2}/.test(m2)) {
                return m1+m2;
              } else {
                log.debug('Found local image %s in %s', m2, doc.id);
                var type = mime.lookup(m2);
                try {
                  return m1+'data:' + type + ';base64,' + fs.readFileSync(path.join(path.dirname(doc.fileInfo.filePath), m2)).toString('base64');
                } catch (e) {
                  log.error('Can\'t read file: %s', e.message);
                  return m1+m2;
                }
              }
            })
          });
        });
    }
  };
};