index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. 'use strict';
  2. /**
  3. * Module dependencies.
  4. */
  5. var utils = require('./lib/utils');
  6. var packageJson = require('./package.json');
  7. var fs = require('fs');
  8. var path = require('path');
  9. var inline = require('web-resource-inliner');
  10. var juiceClient = require('./client');
  11. var cheerio = require('./lib/cheerio');
  12. var juice = juiceClient;
  13. module.exports = juice;
  14. juice.version = packageJson.version;
  15. juice.Selector = utils.Selector;
  16. juice.Property = utils.Property;
  17. juice.utils = utils;
  18. juice.ignoredPseudos = juiceClient.ignoredPseudos;
  19. juice.widthElements = juiceClient.widthElements;
  20. juice.tableElements = juiceClient.tableElements;
  21. juice.nonVisualElements = juiceClient.nonVisualElements;
  22. juice.styleToAttribute = juiceClient.styleToAttribute;
  23. juice.juiceDocument = juiceClient.juiceDocument;
  24. juice.inlineDocument = juiceClient.inlineDocument;
  25. juice.inlineContent = juiceClient.inlineContent;
  26. juice.juiceFile = juiceFile;
  27. juice.juiceResources = juiceResources;
  28. juice.inlineExternal = inlineExternal;
  29. juice.codeBlocks = cheerio.codeBlocks;
  30. function juiceFile(filePath, options, callback) {
  31. // set default options
  32. fs.readFile(filePath, 'utf8', function(err, content) {
  33. if (err) {
  34. return callback(err);
  35. }
  36. options = utils.getDefaultOptions(options); // so we can mutate options without guilt
  37. // Optional support for codeBlocks within optionsFile
  38. if (options.codeBlocks) {
  39. Object.keys(options.codeBlocks).forEach(function(key) {
  40. juice.codeBlocks[key] = options.codeBlocks[key];
  41. });
  42. }
  43. if (!options.webResources.relativeTo) {
  44. var rel = path.dirname(path.relative(process.cwd(),filePath));
  45. options.webResources.relativeTo = rel;
  46. }
  47. juiceResources(content, options, callback);
  48. });
  49. }
  50. function inlineExternal(html, inlineOptions, callback) {
  51. var options = Object.assign({fileContent: html}, inlineOptions);
  52. inline.html(options, callback);
  53. }
  54. function juiceResources(html, options, callback) {
  55. options = utils.getDefaultOptions(options);
  56. var onInline = function(err, html) {
  57. if (err) {
  58. return callback(err);
  59. }
  60. return callback(null,
  61. cheerio(html, { xmlMode: options && options.xmlMode}, juiceClient.juiceDocument, [options])
  62. );
  63. };
  64. options.webResources.relativeTo = options.webResources.relativeTo || options.url; // legacy support
  65. inlineExternal(html, options.webResources, onInline);
  66. }