asset.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. const fs = require('hexo-fs');
  3. const Promise = require('bluebird');
  4. const pathFn = require('path');
  5. const chalk = require('chalk');
  6. function assetGenerator(locals) {
  7. const self = this;
  8. function process(name) {
  9. return Promise.filter(self.model(name).toArray(), asset => fs.exists(asset.source).then(exist => {
  10. if (exist) return exist;
  11. return asset.remove().thenReturn(exist);
  12. })).map(asset => {
  13. const source = asset.source;
  14. let path = asset.path;
  15. const data = {
  16. modified: asset.modified
  17. };
  18. if (asset.renderable && self.render.isRenderable(path)) {
  19. // Replace extension name if the asset is renderable
  20. const extname = pathFn.extname(path);
  21. const filename = path.substring(0, path.length - extname.length);
  22. path = `${filename}.${self.render.getOutput(path)}`;
  23. data.data = () => self.render.render({
  24. path: source,
  25. toString: true
  26. }).catch(err => {
  27. self.log.error({err}, 'Asset render failed: %s', chalk.magenta(path));
  28. });
  29. } else {
  30. data.data = () => fs.createReadStream(source);
  31. }
  32. return {
  33. path,
  34. data
  35. };
  36. });
  37. }
  38. return Promise.all([
  39. process('Asset'),
  40. process('PostAsset')
  41. ]).then(data => Array.prototype.concat.apply([], data));
  42. }
  43. module.exports = assetGenerator;