0
# File Processing
1
2
Asynchronous dimension extraction directly from image files with configurable concurrency control. This approach is recommended for local file operations as it provides better performance and resource management.
3
4
## Capabilities
5
6
### Asynchronous File Dimension Extraction
7
8
Extracts dimensions from image files asynchronously with automatic concurrency management.
9
10
```typescript { .api }
11
/**
12
* Extract dimensions from image file asynchronously
13
* @param filePath - Relative or absolute path to image file
14
* @returns Promise resolving to dimension data
15
* @throws Error if file doesn't exist, is empty, or unsupported format
16
*/
17
function imageSizeFromFile(filePath: string): Promise<ISizeCalculationResult>;
18
19
interface ISizeCalculationResult {
20
/** Image width in pixels */
21
width: number;
22
/** Image height in pixels */
23
height: number;
24
/** JPEG EXIF orientation (1-8) if present */
25
orientation?: number;
26
/** Detected image format string */
27
type?: string;
28
/** Array of all sizes for multi-size formats (ICO, CUR, HEIF) */
29
images?: ISize[];
30
}
31
```
32
33
**Usage Examples:**
34
35
```typescript
36
import { imageSizeFromFile } from "image-size/fromFile";
37
38
// Basic file processing
39
const dimensions = await imageSizeFromFile("photos/vacation.jpg");
40
console.log(`${dimensions.width}x${dimensions.height}`); // 4032x3024
41
console.log(`Type: ${dimensions.type}`); // Type: jpg
42
43
// Process multiple files
44
const files = ["image1.png", "image2.jpg", "image3.webp"];
45
const results = await Promise.all(
46
files.map(file => imageSizeFromFile(file))
47
);
48
results.forEach((result, index) => {
49
console.log(`${files[index]}: ${result.width}x${result.height}`);
50
});
51
52
// Handle relative and absolute paths
53
const relativeResult = await imageSizeFromFile("./assets/logo.png");
54
const absoluteResult = await imageSizeFromFile("/home/user/pictures/photo.jpg");
55
56
// Multi-size formats
57
const iconInfo = await imageSizeFromFile("favicon.ico");
58
console.log(`Main: ${iconInfo.width}x${iconInfo.height}`); // Largest size
59
if (iconInfo.images) {
60
console.log("Available sizes:");
61
iconInfo.images.forEach(size =>
62
console.log(` ${size.width}x${size.height}`)
63
);
64
}
65
66
// JPEG orientation handling
67
const photoInfo = await imageSizeFromFile("rotated-photo.jpg");
68
if (photoInfo.orientation) {
69
console.log(`Orientation: ${photoInfo.orientation}`); // 1-8 EXIF value
70
}
71
```
72
73
### Concurrency Control
74
75
Manage the number of concurrent file operations to prevent resource exhaustion.
76
77
```typescript { .api }
78
/**
79
* Set maximum concurrent file operations
80
* @param c - Maximum number of concurrent file reads (default: 100)
81
* @returns void
82
*/
83
function setConcurrency(c: number): void;
84
```
85
86
**Usage Examples:**
87
88
```typescript
89
import { imageSizeFromFile, setConcurrency } from "image-size/fromFile";
90
91
// Default concurrency is 100
92
console.log("Using default concurrency (100)");
93
94
// Reduce concurrency for resource-constrained environments
95
setConcurrency(10);
96
97
// Process many files with controlled concurrency
98
const imageFiles = Array.from({ length: 1000 }, (_, i) => `image${i}.jpg`);
99
const startTime = Date.now();
100
101
const results = await Promise.all(
102
imageFiles.map(file => imageSizeFromFile(file))
103
);
104
105
console.log(`Processed ${results.length} images in ${Date.now() - startTime}ms`);
106
107
// Increase concurrency for high-performance environments
108
setConcurrency(500);
109
110
// For batch processing scenarios
111
async function processBatch(files: string[], batchSize: number = 50) {
112
setConcurrency(batchSize);
113
114
const results = [];
115
for (let i = 0; i < files.length; i += batchSize) {
116
const batch = files.slice(i, i + batchSize);
117
const batchResults = await Promise.all(
118
batch.map(file => imageSizeFromFile(file))
119
);
120
results.push(...batchResults);
121
console.log(`Processed batch ${Math.floor(i / batchSize) + 1}`);
122
}
123
124
return results;
125
}
126
```
127
128
## Error Handling
129
130
File processing can encounter various error conditions:
131
132
```typescript
133
import { imageSizeFromFile } from "image-size/fromFile";
134
135
try {
136
const result = await imageSizeFromFile("nonexistent.jpg");
137
} catch (error) {
138
console.log(error.message); // ENOENT: no such file or directory
139
}
140
141
try {
142
const result = await imageSizeFromFile("empty-file.jpg");
143
} catch (error) {
144
console.log(error.message); // "Empty file"
145
}
146
147
try {
148
const result = await imageSizeFromFile("corrupted.jpg");
149
} catch (error) {
150
console.log(error.message); // "unsupported file type: undefined"
151
}
152
153
// Handle errors gracefully
154
async function safeImageSize(filePath: string) {
155
try {
156
return await imageSizeFromFile(filePath);
157
} catch (error) {
158
console.error(`Failed to process ${filePath}:`, error.message);
159
return null;
160
}
161
}
162
163
// Batch processing with error handling
164
async function processImagesWithErrors(files: string[]) {
165
const results = await Promise.allSettled(
166
files.map(file => imageSizeFromFile(file))
167
);
168
169
const successful = results
170
.filter(result => result.status === 'fulfilled')
171
.map(result => (result as PromiseFulfilledResult<any>).value);
172
173
const failed = results
174
.filter(result => result.status === 'rejected')
175
.map((result, index) => ({
176
file: files[index],
177
error: (result as PromiseRejectedResult).reason.message
178
}));
179
180
return { successful, failed };
181
}
182
```
183
184
## Performance Notes
185
186
- **Memory Efficient**: Reads only image headers (up to 512KB max)
187
- **Concurrency Control**: Default limit of 100 prevents file descriptor exhaustion
188
- **Non-blocking**: Asynchronous operations don't block the event loop
189
- **Queue Management**: Internal queue system manages file operations efficiently
190
- **Resource Management**: Automatically closes file handles after reading
191
192
## CLI Usage
193
194
The package includes a command-line interface for quick image inspection:
195
196
```bash
197
# Install globally or use npx
198
npm install -g image-size
199
# or
200
npx image-size image1.jpg image2.png
201
202
# Example output:
203
# 1920x1080 - vacation.jpg (jpg)
204
# 256x256 - logo.png (png)
205
# 64x64 - favicon.ico (ico)
206
# 128x128 - favicon.ico (ico)
207
```
208
209
The CLI tool uses `imageSizeFromFile` internally and displays all available sizes for multi-size formats.