Нет описания

index.js 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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.juiceFile = juiceFile;
  19. juice.juiceResources = juiceResources;
  20. juice.inlineExternal = inlineExternal;
  21. function juiceFile(filePath, options, callback) {
  22. // set default options
  23. fs.readFile(filePath, 'utf8', function(err, content) {
  24. if (err) {
  25. return callback(err);
  26. }
  27. options = utils.getDefaultOptions(options); // so we can mutate options without guilt
  28. // Optional support for codeBlocks within optionsFile
  29. if (options.codeBlocks) {
  30. Object.keys(options.codeBlocks).forEach(function(key) {
  31. juice.codeBlocks[key] = options.codeBlocks[key];
  32. });
  33. }
  34. if (!options.webResources.relativeTo) {
  35. var rel = path.dirname(path.relative(process.cwd(),filePath));
  36. options.webResources.relativeTo = rel;
  37. }
  38. juiceResources(content, options, callback);
  39. });
  40. }
  41. function inlineExternal(html, inlineOptions, callback) {
  42. var options = Object.assign({fileContent: html}, inlineOptions);
  43. inline.html(options, callback);
  44. }
  45. function juiceResources(html, options, callback) {
  46. options = utils.getDefaultOptions(options);
  47. var onInline = function(err, html) {
  48. if (err) {
  49. return callback(err);
  50. }
  51. return callback(null,
  52. cheerio(html, { xmlMode: options && options.xmlMode}, juiceClient.juiceDocument, [options])
  53. );
  54. };
  55. options.webResources.relativeTo = options.webResources.relativeTo || options.url; // legacy support
  56. inlineExternal(html, options.webResources, onInline);
  57. }