minify.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. const DIR = __dirname + '/';
  3. const fs = require('fs');
  4. const path = require('path');
  5. const {promisify} = require('util');
  6. const tryToCatch = require('try-to-catch');
  7. const readFile = promisify(fs.readFile);
  8. const log = require('debug')('minify');
  9. for (const name of ['js', 'html', 'css', 'img']) {
  10. minify[name] = require(DIR + name);
  11. }
  12. module.exports = minify;
  13. function check(name) {
  14. if (!name)
  15. throw Error('name could not be empty!');
  16. }
  17. async function minify(name) {
  18. const EXT = ['js', 'html', 'css'];
  19. check(name);
  20. const ext = path.extname(name).slice(1);
  21. const is = ~EXT.indexOf(ext);
  22. if (!is)
  23. throw Error(`File type "${ext}" not supported.`);
  24. log('optimizing ' + path.basename(name));
  25. return optimize(name);
  26. }
  27. function getName(file) {
  28. const notObj = typeof file !== 'object';
  29. if (notObj)
  30. return file;
  31. return Object.keys(file)[0];
  32. }
  33. /**
  34. * function minificate js,css and html files
  35. *
  36. * @param files - js, css or html file path
  37. */
  38. async function optimize(file) {
  39. check(file);
  40. const name = getName(file);
  41. log('reading file ' + path.basename(name));
  42. const data = await readFile(name, 'utf8');
  43. return onDataRead(file, data);
  44. }
  45. /**
  46. * Processing of files
  47. * @param fileData {name, data}
  48. */
  49. async function onDataRead(filename, data) {
  50. log('file ' + path.basename(filename) + ' read');
  51. const ext = path.extname(filename).replace(/^\./, '');
  52. const optimizedData = await minify[ext](data);
  53. let b64Optimize;
  54. if (ext === 'css')
  55. [, b64Optimize] = await tryToCatch(minify.img, filename, optimizedData);
  56. return b64Optimize || optimizedData;
  57. }