Skip to content

Commit

Permalink
feat: added exception handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Mike Mellor committed Jan 27, 2023
1 parent f594e44 commit 5f02a45
Showing 1 changed file with 46 additions and 21 deletions.
67 changes: 46 additions & 21 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@ import puppeteer from "puppeteer-core";
import path from "path";

export async function fit(srcs, dests, options = { silent: false }){
if(typeof srcs !== 'string' && !Array.isArray(srcs)){
throw new Error('src must be an array or a string.');
}

if(typeof dests !== 'string' && !Array.isArray(dests)){
throw new Error('dest must be an array or a string.');
}

let opts = Object.assign({
puppeteer: {
args: ['--headless', '--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'],
Expand All @@ -12,34 +20,51 @@ export async function fit(srcs, dests, options = { silent: false }){

srcs = Array.isArray(srcs) ? srcs : [srcs];
dests = Array.isArray(dests) ? dests : [dests];
let inputs;

inputs = srcs.reduce((concat, src, i) => {
let arr;
if(srcs.length !== dests.length && dests.find(d => path.extname(d) === '.svg')){
throw new Error('uneven number of src and dest files.');
}

let inputs;

if(fs.existsSync(src)){
if(fs.lstatSync(src).isDirectory()){
arr = fs.readdirSync(src).map(d => ({src: `${src}/${d}`}));
} else {
arr = [{src}];
try{
inputs = srcs.reduce((concat, src, i) => {
let arr = [];

if(fs.existsSync(src)){
if(fs.lstatSync(src).isDirectory()){
arr = fs.readdirSync(src).map(d => ({src: `${src}/${d}`}));
} else {
arr = [{src}];
}
}
}

let dest = dests[i % dests.length];
let destIsFile = path.extname(dest) === '.svg';
let destPath = destIsFile ? path.dirname(dest) : dest;
let dest = dests[i % dests.length];
let destIsFile = path.extname(dest) !== '';
let destPath = destIsFile ? path.dirname(dest) : dest;

fs.mkdirpSync(destPath);
fs.mkdirpSync(destPath);

arr = arr.map(input => {
return {
src: input.src,
dest: destIsFile ? dest : `${destPath}/${path.basename(input.src)}`
};
});
arr = arr.map(input => {
return {
src: input.src,
dest: destIsFile ? dest : `${destPath}/${path.basename(input.src)}`
};
});

return concat.concat(arr);
}, []);
} catch(e){console.log(e);}

return concat.concat(arr);
}, []);
inputs.forEach(d => {
if(path.extname(d.src) !== '.svg'){
throw new Error('some srcs are non svg files.');
}

if(path.extname(d.dest) !== '.svg'){
throw new Error('some dest files have a non svg extension.');
}
});

const browser = await puppeteer.launch({
executablePath: opts.puppeteer.executablePath,
Expand Down

0 comments on commit 5f02a45

Please sign in to comment.