UNPKG

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