Skip to content

Commit 057cf1e

Browse files
committed
Refactor error handling
1 parent 40fad7a commit 057cf1e

File tree

6 files changed

+128
-72
lines changed

6 files changed

+128
-72
lines changed

slice.cjs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,23 @@ function main() {
1212
alias: 'filename',
1313
describe: 'Input image filename',
1414
type: 'string',
15+
coerce: (value) => {
16+
if (Array.isArray(value)) {
17+
value = value.join('');
18+
}
19+
return value;
20+
},
1521
})
1622
.option('i', {
1723
alias: 'folderPath',
1824
describe: 'Input folder',
1925
type: 'string',
26+
coerce: (value) => {
27+
if (Array.isArray(value)) {
28+
value = value.join('');
29+
}
30+
return value;
31+
},
2032
})
2133
.option('w', {
2234
alias: 'width',
@@ -108,8 +120,8 @@ function main() {
108120
numCores = Math.min(numCores, 16); // Max 16
109121
(0, processPath_1.processPath)(options.folderPath, options, numCores);
110122
} else {
111-
console.log(
112-
'Requires either `filename` or `folderPath`. Run `slice --help` for help.',
123+
console.error(
124+
'Error: Requires either `filename` or `folderPath`. Run `slice --help` for help.',
113125
);
114126
}
115127
}

src/slice.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,23 @@ function main() {
1313
alias: 'filename',
1414
describe: 'Input image filename',
1515
type: 'string',
16+
coerce: (value) => {
17+
if (Array.isArray(value)) {
18+
value = value.join('');
19+
}
20+
return value;
21+
},
1622
})
1723
.option('i', {
1824
alias: 'folderPath',
1925
describe: 'Input folder',
2026
type: 'string',
27+
coerce: (value) => {
28+
if (Array.isArray(value)) {
29+
value = value.join('');
30+
}
31+
return value;
32+
},
2133
})
2234
.option('w', {
2335
alias: 'width',
@@ -110,8 +122,8 @@ function main() {
110122
numCores = Math.min(numCores, 16); // Max 16
111123
processPath(options.folderPath, options, numCores);
112124
} else {
113-
console.log(
114-
'Requires either `filename` or `folderPath`. Run `slice --help` for help.',
125+
console.error(
126+
'Error: Requires either `filename` or `folderPath`. Run `slice --help` for help.',
115127
);
116128
}
117129
}

src/utils/processImage.ts

Lines changed: 57 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ import * as fs from 'fs';
33
import * as path from 'path';
44
import { workerData, isMainThread } from 'worker_threads';
55

6-
const outputFolder = 'output';
6+
function errorCallback(err: unknown) {
7+
if (err) {
8+
console.error(err);
9+
}
10+
}
711

812
/**
913
* Function to slice an image into smaller segments
@@ -18,12 +22,11 @@ export function sliceImage(
1822
cubic: boolean,
1923
skipExtCheck?: boolean,
2024
): void {
21-
Jimp.read(filename, (err, image) => {
22-
if (err && skipExtCheck) {
23-
console.error(err);
24-
} else {
25+
Jimp.read(filename)
26+
.then((image) => {
2527
// Continue slicing if image is successfully read
2628
if (image) {
29+
skipExtCheck = true;
2730
continueSlicing(
2831
image,
2932
width,
@@ -35,41 +38,53 @@ export function sliceImage(
3538
filename,
3639
);
3740
}
38-
}
39-
});
40-
41-
if (skipExtCheck) {
42-
return;
43-
}
41+
})
42+
.catch((err) => {
43+
if (skipExtCheck) {
44+
console.error(err);
45+
}
46+
})
47+
.finally(() => {
48+
if (skipExtCheck) {
49+
return;
50+
}
4451

45-
// Check for supported image formats if skipExtCheck is false
46-
const supportedFormats = ['.png', '.gif', '.jpg', '.jpeg'];
47-
let foundImage = false;
48-
49-
// Attempt to read the image with different extensions
50-
supportedFormats.forEach(async (ext, index) => {
51-
const fullFilename = filename + ext;
52-
if (!foundImage) {
53-
try {
54-
const image = await Jimp.read(fullFilename);
55-
foundImage = true;
56-
continueSlicing(
57-
image,
58-
width,
59-
height,
60-
canvasWidth,
61-
canvasHeight,
62-
scale,
63-
cubic,
64-
fullFilename,
52+
// Check for supported image formats if skipExtCheck is false
53+
const supportedFormats = ['.png', '.gif', '.jpg', '.jpeg'];
54+
let foundImage = false;
55+
56+
// Attempt to read the image with different extensions
57+
const promises = supportedFormats.map((ext) => {
58+
const fullFilename = filename + ext;
59+
return (
60+
Jimp.read(fullFilename)
61+
.then((image) => {
62+
foundImage = true;
63+
continueSlicing(
64+
image,
65+
width,
66+
height,
67+
canvasWidth,
68+
canvasHeight,
69+
scale,
70+
cubic,
71+
fullFilename,
72+
);
73+
})
74+
// Silence errors since we'll handle them later
75+
.catch(() => {})
6576
);
66-
} catch (err) {}
67-
68-
if (!foundImage && index === supportedFormats.length - 1) {
69-
console.error(`Could not find ${filename}`);
70-
}
71-
}
72-
});
77+
});
78+
79+
// Wait for all promises to be resolved
80+
Promise.all(promises)
81+
.then(() => {
82+
if (!foundImage) {
83+
console.error(`Error: Could not find ${filename}`);
84+
}
85+
})
86+
.catch(errorCallback);
87+
});
7388
}
7489

7590
/**
@@ -86,6 +101,7 @@ function continueSlicing(
86101
inputFilename: string,
87102
): void {
88103
console.time('Done in');
104+
89105
// If height is not specified, use width as height
90106
height = height || width;
91107

@@ -97,6 +113,7 @@ function continueSlicing(
97113
const verticalSlices = Math.ceil(imageHeight / height);
98114

99115
// Create a folder for output if it doesn't exist
116+
const outputFolder = 'output';
100117
if (!fs.existsSync(outputFolder)) {
101118
fs.mkdirSync(outputFolder);
102119
}
@@ -141,15 +158,15 @@ function continueSlicing(
141158
cubic ? Jimp.RESIZE_BICUBIC : Jimp.RESIZE_NEAREST_NEIGHBOR,
142159
);
143160
}
144-
canvas.write(outputFilename);
161+
canvas.write(outputFilename, errorCallback);
145162
} else {
146163
if (scale !== 1) {
147164
slice.scale(
148165
scale,
149166
cubic ? Jimp.RESIZE_BICUBIC : Jimp.RESIZE_NEAREST_NEIGHBOR,
150167
);
151168
}
152-
slice.write(outputFilename);
169+
slice.write(outputFilename, errorCallback);
153170
}
154171

155172
console.log(`Slice saved: ${outputFilename}`);

src/utils/processPath.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ export function processPath(
1010
options: Options,
1111
maxWorkers: number,
1212
): void {
13+
console.log({ directoryPath });
1314
const workerPool = new WorkerPool(maxWorkers);
1415

1516
// Read the contents of the directory

utils/processImage.js

Lines changed: 41 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -5,42 +5,54 @@ const Jimp = require("jimp");
55
const fs = require("fs");
66
const path = require("path");
77
const worker_threads_1 = require("worker_threads");
8-
const outputFolder = 'output';
8+
function errorCallback(err) {
9+
if (err) {
10+
console.error(err);
11+
}
12+
}
913
/**
1014
* Function to slice an image into smaller segments
1115
*/
1216
function sliceImage(filename, width, height, canvasWidth, canvasHeight, scale, cubic, skipExtCheck) {
13-
Jimp.read(filename, (err, image) => {
14-
if (err && skipExtCheck) {
17+
Jimp.read(filename)
18+
.then((image) => {
19+
// Continue slicing if image is successfully read
20+
if (image) {
21+
skipExtCheck = true;
22+
continueSlicing(image, width, height, canvasWidth, canvasHeight, scale, cubic, filename);
23+
}
24+
})
25+
.catch((err) => {
26+
if (skipExtCheck) {
1527
console.error(err);
1628
}
17-
else {
18-
// Continue slicing if image is successfully read
19-
if (image) {
20-
continueSlicing(image, width, height, canvasWidth, canvasHeight, scale, cubic, filename);
21-
}
29+
})
30+
.finally(() => {
31+
if (skipExtCheck) {
32+
return;
2233
}
23-
});
24-
if (skipExtCheck) {
25-
return;
26-
}
27-
// Check for supported image formats if skipExtCheck is false
28-
const supportedFormats = ['.png', '.gif', '.jpg', '.jpeg'];
29-
let foundImage = false;
30-
// Attempt to read the image with different extensions
31-
supportedFormats.forEach(async (ext, index) => {
32-
const fullFilename = filename + ext;
33-
if (!foundImage) {
34-
try {
35-
const image = await Jimp.read(fullFilename);
34+
// Check for supported image formats if skipExtCheck is false
35+
const supportedFormats = ['.png', '.gif', '.jpg', '.jpeg'];
36+
let foundImage = false;
37+
// Attempt to read the image with different extensions
38+
const promises = supportedFormats.map((ext) => {
39+
const fullFilename = filename + ext;
40+
return (Jimp.read(fullFilename)
41+
.then((image) => {
3642
foundImage = true;
3743
continueSlicing(image, width, height, canvasWidth, canvasHeight, scale, cubic, fullFilename);
44+
})
45+
// Silence errors since we'll handle them later
46+
.catch(() => { }));
47+
});
48+
// Wait for all promises to be resolved
49+
Promise.all(promises)
50+
.then(() => {
51+
if (!foundImage) {
52+
console.error(`Error: Could not find ${filename}`);
3853
}
39-
catch (err) { }
40-
if (!foundImage && index === supportedFormats.length - 1) {
41-
console.error(`Could not find ${filename}`);
42-
}
43-
}
54+
})
55+
.catch(errorCallback);
4456
});
4557
}
4658
exports.sliceImage = sliceImage;
@@ -57,6 +69,7 @@ function continueSlicing(image, width, height, canvasWidth, canvasHeight, scale,
5769
const horizontalSlices = Math.ceil(imageWidth / width);
5870
const verticalSlices = Math.ceil(imageHeight / height);
5971
// Create a folder for output if it doesn't exist
72+
const outputFolder = 'output';
6073
if (!fs.existsSync(outputFolder)) {
6174
fs.mkdirSync(outputFolder);
6275
}
@@ -84,13 +97,13 @@ function continueSlicing(image, width, height, canvasWidth, canvasHeight, scale,
8497
if (scale !== 1) {
8598
canvas.scale(scale, cubic ? Jimp.RESIZE_BICUBIC : Jimp.RESIZE_NEAREST_NEIGHBOR);
8699
}
87-
canvas.write(outputFilename);
100+
canvas.write(outputFilename, errorCallback);
88101
}
89102
else {
90103
if (scale !== 1) {
91104
slice.scale(scale, cubic ? Jimp.RESIZE_BICUBIC : Jimp.RESIZE_NEAREST_NEIGHBOR);
92105
}
93-
slice.write(outputFilename);
106+
slice.write(outputFilename, errorCallback);
94107
}
95108
console.log(`Slice saved: ${outputFilename}`);
96109
}

utils/processPath.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const workerPool_1 = require("./workerPool");
88
* Processes all files in the specified directory with the given image processing options.
99
*/
1010
function processPath(directoryPath, options, maxWorkers) {
11+
console.log({ directoryPath });
1112
const workerPool = new workerPool_1.WorkerPool(maxWorkers);
1213
// Read the contents of the directory
1314
fs.readdir(directoryPath, (err, files) => {

0 commit comments

Comments
 (0)