index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. const {promisify} = require('util');
  3. const path = require('path');
  4. const fs = require('graceful-fs');
  5. const fileType = require('file-type');
  6. const globby = require('globby');
  7. const makeDir = require('make-dir');
  8. const pPipe = require('p-pipe');
  9. const replaceExt = require('replace-ext');
  10. const junk = require('junk');
  11. const readFile = promisify(fs.readFile);
  12. const writeFile = promisify(fs.writeFile);
  13. const handleFile = async (sourcePath, {destination, plugins = []}) => {
  14. if (plugins && !Array.isArray(plugins)) {
  15. throw new TypeError('The `plugins` option should be an `Array`');
  16. }
  17. let data = await readFile(sourcePath);
  18. data = await (plugins.length > 0 ? pPipe(...plugins)(data) : data);
  19. let destinationPath = destination ? path.join(destination, path.basename(sourcePath)) : undefined;
  20. destinationPath = (fileType(data) && fileType(data).ext === 'webp') ? replaceExt(destinationPath, '.webp') : destinationPath;
  21. const returnValue = {
  22. data,
  23. sourcePath,
  24. destinationPath
  25. };
  26. if (!destinationPath) {
  27. return returnValue;
  28. }
  29. await makeDir(path.dirname(returnValue.destinationPath));
  30. await writeFile(returnValue.destinationPath, returnValue.data);
  31. return returnValue;
  32. };
  33. module.exports = async (input, {glob = true, ...options} = {}) => {
  34. if (!Array.isArray(input)) {
  35. throw new TypeError(`Expected an \`Array\`, got \`${typeof input}\``);
  36. }
  37. const filePaths = glob ? await globby(input, {onlyFiles: true}) : input;
  38. return Promise.all(
  39. filePaths
  40. .filter(filePath => junk.not(path.basename(filePath)))
  41. .map(async filePath => {
  42. try {
  43. return await handleFile(filePath, options);
  44. } catch (error) {
  45. error.message = `Error occurred when handling file: ${input}\n\n${error.stack}`;
  46. throw error;
  47. }
  48. })
  49. );
  50. };
  51. module.exports.buffer = async (input, {plugins = []} = {}) => {
  52. if (!Buffer.isBuffer(input)) {
  53. throw new TypeError(`Expected a \`Buffer\`, got \`${typeof input}\``);
  54. }
  55. if (plugins.length === 0) {
  56. return input;
  57. }
  58. return pPipe(...plugins)(input);
  59. };