@d0paminedriven/fs 6.0.1 → 6.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,100 +1,352 @@
1
1
  # @d0paminedriven/fs
2
2
 
3
- > *“Don’t sweat the small stuff; just write your damn files.”*
3
+ > **The filesystem utilities that eliminate entire categories of bugs from your codebase.**
4
4
 
5
- Let's be real, you likely already have a project manager breathing down your neck for updates on the hour, JIRA ticket blues bringing you down, Teams/Slack notification pings plaguing your dreams, the "hey, got five minutes?" guy breaking your flow state on the daily, and nth other pressing issues on your mind mid-development.
5
+ ## 🎯 Why This Package Exists
6
6
 
7
- These situations are all annoying af, which is why this package seamlessly ensures that targeted output paths exist for you (if they don't exist yet, they will before your file is written). Whether you're using `writeFileAsync`, `fetchRemoteWriteLocalLargeFiles`, or `withWs`, this package has you covered no matter how deep your targeted output paths go. Unfortunately, this package *can't* help with that pesky PM or that flow-breaking co-worker (yet--PRs welcome).
7
+ **Stop checking if directories exist.** Stop worrying about MIME types. Stop blowing up your RAM with large files. Stop writing the same filesystem boilerplate over and over.
8
8
 
9
- Want to grab some remote files? Throw any file size its way — no problemo — just use the `fetchRemoteWriteLocalLargeFiles` method. (Proceed with caution in the >=gigabyte range. If your setup can handle it, then by all means.)
9
+ This package solves real problems that `fs-extra` and other utilities ignore:
10
+
11
+ - ✅ **Atomic directory creation with write operations** - One method, zero directory anxiety
12
+ - ✅ **Intelligent MIME type handling** - Bidirectional mapping with compile-time safety
13
+ - ✅ **Memory-safe remote asset fetching** - Stream gigabyte files without fear
14
+ - ✅ **Native image dimension extraction** - Get width, height, format without dependencies
15
+ - ✅ **Tmp directory management** - Complete utilities for temporary file operations
16
+ - ✅ **Type-safe throughout** - Full TypeScript with literal types and inference
17
+
18
+ ## 🚀 The Revolutionary `withWs` Method
19
+
20
+ **This single method has eliminated "directory doesn't exist" errors for 3+ years:**
21
+
22
+ ```typescript
23
+ // What everyone else does (including fs-extra):
24
+ await fs.mkdir('/deep/nested/path', { recursive: true });
25
+ const stream = fs.createWriteStream('/deep/nested/path/file.json');
26
+ stream.write(data);
27
+ // 3 operations, multiple points of failure, mental overhead
28
+
29
+ // What withWs does:
30
+ fs.withWs('/deep/nested/path/file.json', data);
31
+ // ONE operation. Directories created atomically with write stream.
32
+ // No await needed. No directory checks. Just works.
33
+ ```
10
34
 
11
35
  ---
12
36
 
13
- ## 🚀 Quickstart
37
+ ## 📦 Installation
38
+
39
+ ```bash
40
+ pnpm add @d0paminedriven/fs
41
+ # or
42
+ npm install @d0paminedriven/fs
43
+ ```
44
+
45
+ ## 🔥 Core Features
14
46
 
15
- ```ts
16
- import { Fs } from "@d0paminedriven/fs";
47
+ ### 1. Smart Remote Asset Fetching
17
48
 
18
- // Set your cwd (project root recommended)
49
+ **Handles URLs without extensions intelligently:**
50
+
51
+ ```typescript
19
52
  const fs = new Fs(process.cwd());
20
53
 
21
- /** Write to a nested file path (no mkdirp needed) */
22
- await fs.writeFileAsync("public/assets/images/foo/bar.jpg", myImageBuffer);
23
- // No error, no “does this folder exist?”, no drama
54
+ // URLs with no extension? No problem!
55
+ // Automatically detects MIME type from Content-Type header
56
+ await fs.fetchRemoteWriteLocalLargeFiles(
57
+ "https://api.example.com/asset/12345", // No extension in URL
58
+ "public/assets/downloaded-file" // Extension auto-detected
59
+ );
60
+ // Result: public/assets/downloaded-file.png (if Content-Type was image/png)
24
61
 
25
- /** Fetch and save a massive remote asset */
62
+ // Streams large files without memory explosion
26
63
  await fs.fetchRemoteWriteLocalLargeFiles(
27
- "https://cdn.example.com/big-model.glb",
28
- "public/models/my-big-model"
64
+ "https://cdn.example.com/huge-video.mp4", // 2GB file? No problem
65
+ "public/videos/my-video"
29
66
  );
30
- // Handles directories, streams file to disk, and never blows up your RAM
67
+ ```
68
+
69
+ ### 2. Native Image Dimension Extraction
70
+
71
+ **Get image dimensions without heavy dependencies:**
72
+
73
+ ```typescript
74
+ // Extract width, height, and format from any image
75
+ const imageInfo = fs.getImageSize("public/images/hero.jpg");
76
+ console.log(imageInfo);
77
+ // { width: 1920, height: 1080, type: "jpeg" }
78
+
79
+ // Works with PNG, JPEG, GIF, BMP, WebP, AVIF
80
+ // No ImageMagick, no Sharp needed for basic dimension reading
81
+ ```
31
82
 
32
- /** Read every file in a directory */
33
- const files = fs.readDir("public/assets/images", { recursive: true });
83
+ ### 3. Intelligent MIME Type System
34
84
 
35
- /** Unlink a file (with existence check) */
36
- await fs.unlink("public/assets/old/unused.txt");
85
+ ```typescript
86
+ // Bidirectional MIME mapping with full type safety
87
+ const mimeType = fs.getMimeTypeForPath("file.tsx"); // "text/tsx"
88
+ const extension = fs.mimeToExt("application/pdf"); // "pdf"
37
89
 
38
- /** Need a wait utility for your script? */
39
- await fs.wait(2000); // waits 2 seconds
90
+ // Handles edge cases elegantly
91
+ fs.getMimeTypeForPath("no-extension"); // "application/octet-stream"
92
+ fs.mimeToExt("image/jpeg"); // "jpg" (returns common extension)
93
+ ```
94
+
95
+ ### 4. Tmp Directory Management Suite
96
+
97
+ ```typescript
98
+ // Write to tmp with automatic cleanup
99
+ const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
100
+
101
+ // Scan tmp directory (non-recursive by default to avoid permission issues)
102
+ const tmpFiles = fs.scanTmp("session-"); // Find all session files
103
+
104
+ // Extract files from tmp to permanent location
105
+ fs.extractFromTmp("processed-", "./output", {
106
+ cleanupAfter: true // Auto-remove from tmp after extraction
107
+ });
108
+
109
+ // Cleanup old tmp files
110
+ fs.cleanupTmp("cache-", 60 * 60 * 1000); // Remove files older than 1 hour
111
+ ```
112
+
113
+ ### 5. The Legendary `withWs` Method
114
+
115
+ ```typescript
116
+ // Deep nested paths? Complex directory structures? Don't care.
117
+ fs.withWs(
118
+ "output/2024/reports/january/week-1/summary.json",
119
+ JSON.stringify(reportData)
120
+ );
121
+ // Creates all 5 directories if needed, writes file, done.
40
122
 
41
- /** Get the MIME type for any file by extension */
42
- const mime = fs.getMimeTypeForPath("foo.png"); // "image/png"
123
+ // Works with any data type
124
+ fs.withWs("public/images/avatar.png", imageBuffer);
125
+ fs.withWs("logs/error.log", "Error: " + errorMessage);
126
+ fs.withWs("data/binary.dat", binaryData);
43
127
  ```
44
128
 
45
129
  ---
46
130
 
47
- ## 🍳 Recipes / Real-World Scripts
48
-
49
- Need to audit or analyze files, generate a TypeScript object from your assets, or automate asset metadata?
50
- Here’s a dead-simple pattern to iterate off of:
51
-
52
- ```ts
53
-
54
- const files = fs.readDir("public/assets/images", { recursive: true });
55
-
56
- /** Map those files to a typescript object with file names as keys + corresponding file sizes as values */
57
- const arr = Array.of<[string, number]>();
58
-
59
- function generateTsObjOfFileSizes(withExtensions = true) {
60
- try {
61
- files.forEach(function (file) {
62
- const size = fs.fileSizeMb(`public/assets/images/${file}`);
63
- if (withExtensions === false) {
64
- arr.push([file.split(/\./g)[0] ?? file, size]);
65
- } else {
66
- arr.push([file, size]);
67
- }
68
- });
69
- } catch (err) {
70
- if (err instanceof Error) throw new Error(err.message);
71
- else console.error(`generateTsFileOfFileSizes`, err);
72
- } finally {
73
- const tupleArrToObj = Object.fromEntries(arr);
74
- fs.withWs(
75
- `src/utils/file-sizes.ts`,
76
- `export const publicAssetsImagesFileSizesMb = ${JSON.stringify(tupleArrToObj, null, 2)} as const;`
131
+ ## 🎨 Real-World Examples
132
+
133
+ ### Image Asset Pipeline
134
+
135
+ ```typescript
136
+ const fs = new Fs(process.cwd());
137
+
138
+ async function processImageAssets() {
139
+ // Fetch remote images with automatic extension detection
140
+ const imageUrls = [
141
+ "https://api.unsplash.com/photos/random", // No extension!
142
+ "https://cdn.example.com/hero-image", // No extension!
143
+ "https://example.com/logo.avif" // Has extension
144
+ ];
145
+
146
+ for (const url of imageUrls) {
147
+ // Extension auto-detected from Content-Type
148
+ await fs.fetchRemoteWriteLocalLargeFiles(
149
+ url,
150
+ `public/images/${Date.now()}`
77
151
  );
78
152
  }
153
+
154
+ // Get dimensions for all downloaded images
155
+ const images = fs.readDir("public/images");
156
+ const metadata = images.map(img => ({
157
+ file: img,
158
+ ...fs.getImageSize(`public/images/${img}`),
159
+ size: fs.getSize(`public/images/${img}`)
160
+ }));
161
+
162
+ // Generate TypeScript metadata file
163
+ fs.withWs(
164
+ "src/generated/image-metadata.ts",
165
+ `export const imageMetadata = ${JSON.stringify(metadata, null, 2)} as const;`
166
+ );
167
+ }
168
+ ```
169
+
170
+ ### Temporary File Processing
171
+
172
+ ```typescript
173
+ async function processUpload(fileBuffer: Buffer, userId: string) {
174
+ const fs = new Fs(process.cwd());
175
+
176
+ // Generate unique tmp filename
177
+ const tmpName = fs.uniqueTmpName(`upload-${userId}`, "dat");
178
+
179
+ // Write to tmp for processing
180
+ const tmpPath = fs.writeTmp(tmpName, fileBuffer);
181
+
182
+ // Process the file (resize, convert, etc.)
183
+ const processed = await processFile(tmpPath);
184
+
185
+ // Move to permanent storage
186
+ fs.withWs(`uploads/${userId}/${Date.now()}.jpg`, processed);
187
+
188
+ // Cleanup tmp (or let cleanupTmp handle it later)
189
+ fs.cleanupTmp(`upload-${userId}`);
79
190
  }
191
+ ```
192
+
193
+ ### Build-Time Asset Generation
194
+
195
+ ```typescript
196
+ // Generate a manifest of all assets with sizes and dimensions
197
+ function generateAssetManifest() {
198
+ const fs = new Fs(process.cwd());
199
+ const assets: Record<string, any> = {};
200
+
201
+ // Scan all asset directories
202
+ const images = fs.readDir("public/images", { recursive: true });
203
+ const videos = fs.readDir("public/videos", { recursive: true });
204
+
205
+ // Process images
206
+ images.forEach(img => {
207
+ const path = `public/images/${img}`;
208
+ assets[img] = {
209
+ type: "image",
210
+ mime: fs.getMimeTypeForPath(img),
211
+ size: fs.autoFileSizeRaw(path),
212
+ dimensions: fs.getImageSize(path)
213
+ };
214
+ });
215
+
216
+ // Process videos
217
+ videos.forEach(vid => {
218
+ const path = `public/videos/${vid}`;
219
+ assets[vid] = {
220
+ type: "video",
221
+ mime: fs.getMimeTypeForPath(vid),
222
+ size: fs.autoFileSizeRaw(path)
223
+ };
224
+ });
225
+
226
+ // Write manifest (directories auto-created)
227
+ fs.withWs(
228
+ "src/generated/assets/manifest.json",
229
+ JSON.stringify(assets, null, 2)
230
+ );
231
+ }
232
+ ```
233
+
234
+ ## 📊 Performance & Architecture
235
+
236
+ ### Why It's Fast
237
+
238
+ - **Stream-based file operations** - Never loads entire files into memory
239
+ - **Parallel directory creation** - Uses `finally` blocks for guaranteed execution
240
+ - **Zero unnecessary checks** - No redundant `fs.exists()` calls
241
+ - **Optimized MIME lookups** - O(1) bidirectional mapping with Map structures
242
+
243
+ ### Memory Safety
244
+
245
+ ```typescript
246
+ // This won't blow up your RAM, even with a 10GB file
247
+ await fs.fetchRemoteWriteLocalLargeFiles(
248
+ "https://example.com/massive-file.zip",
249
+ "downloads/massive-file"
250
+ );
251
+
252
+ // Internally uses streams:
253
+ // response.body.pipe(fs.createWriteStream(path))
254
+ // Instead of loading entire file into memory
255
+ ```
256
+
257
+ ## 🛠️ Complete API Reference
258
+
259
+ ### Core Methods
260
+
261
+ | Method | Description | Returns |
262
+ |--------|-------------|---------|
263
+ | `withWs(path, data, options?)` | Write with automatic directory creation | `WriteStream` |
264
+ | `writeFileAsync(path, data)` | Async file write with directory creation | `Promise<void>` |
265
+ | `readDir(path, options?)` | Read directory contents | `string[]` |
266
+ | `fileToBuffer(path)` | Read file as Buffer | `Buffer` |
267
+ | `exists(path)` | Check if path exists | `boolean` |
268
+ | `rmFile(path)` | Remove file | `void` |
269
+ | `rmDirSync(path)` | Remove directory | `void` |
270
+
271
+ ### Remote Operations
80
272
 
81
- generateTsObjOfFileSizes();
273
+ | Method | Description | Returns |
274
+ |--------|-------------|---------|
275
+ | `fetchRemoteWriteLocalLargeFiles(url, outputPath)` | Stream remote file to disk | `Promise<void>` |
276
+ | `assetToBufferView(url)` | Fetch remote asset as buffer | `Promise<{buffer, b64, mime}>` |
82
277
 
278
+ ### Image Operations
279
+
280
+ | Method | Description | Returns |
281
+ |--------|-------------|---------|
282
+ | `getImageSize(path)` | Extract image dimensions | `{width, height, type}` |
283
+ | `imageTransform(target, options)` | Transform images with Sharp | `Promise<Buffer>` |
284
+ | `cleanDataUrl(dataUrl)` | Strip data URL prefix | `string` |
285
+ | `b64ToBlob(b64, mime?)` | Convert base64 to Blob | `Blob` |
286
+
287
+ ### MIME Operations
288
+
289
+ | Method | Description | Returns |
290
+ |--------|-------------|---------|
291
+ | `getMimeTypeForPath(path)` | Get MIME type from file path | `string` |
292
+ | `mimeToExt(mime)` | Convert MIME to extension | `string` |
293
+ | `getExtensionForMimeType(mime)` | Get extension from MIME | `string \| undefined` |
294
+
295
+ ### Tmp Directory Operations
296
+
297
+ | Method | Description | Returns |
298
+ |--------|-------------|---------|
299
+ | `writeTmp(filename, data)` | Write to tmp directory | `string` (path) |
300
+ | `readTmp(filename)` | Read from tmp directory | `Buffer` |
301
+ | `scanTmp(pattern?)` | List tmp directory contents | `string[]` |
302
+ | `extractFromTmp(pattern, target, options?)` | Extract files from tmp | `string[]` |
303
+ | `cleanupTmp(pattern, maxAge?)` | Remove tmp files | `number` (removed) |
304
+ | `uniqueTmpName(prefix?, ext?)` | Generate unique tmp filename | `string` |
305
+
306
+ ### Utility Methods
307
+
308
+ | Method | Description | Returns |
309
+ |--------|-------------|---------|
310
+ | `wait(ms)` | Async delay utility | `Promise<void>` |
311
+ | `getSize(path)` | Human-readable file size | `string` |
312
+ | `fileSizeMb(path)` | File size in MB | `number` |
313
+ | `autoFileSizeRaw(path)` | Auto-formatted size object | `{size, unit}` |
314
+ | `chunkArray(array, size)` | Split array into chunks | `T[][]` |
315
+
316
+ ## 🚦 Migration Guide
317
+
318
+ ### From fs-extra
319
+
320
+ ```typescript
321
+ // Before (fs-extra)
322
+ await fs.ensureDir('/path/to/dir');
323
+ await fs.writeFile('/path/to/dir/file.json', data);
324
+
325
+ // After (@d0paminedriven/fs)
326
+ fs.withWs('/path/to/dir/file.json', data);
83
327
  ```
84
328
 
85
- *This outputs a TypeScript object you can use for dashboards, asset analytics, or CI/CD checks:*
329
+ ### From Native fs
330
+
331
+ ```typescript
332
+ // Before (native fs)
333
+ import { mkdir, writeFile } from 'fs/promises';
334
+ await mkdir('/path/to/dir', { recursive: true });
335
+ await writeFile('/path/to/dir/file.json', data);
86
336
 
87
- ```ts
88
- export const fileSizesInMb = {
89
- "chess-atb.png": 1.1277456283569336,
90
- "elegant-stone-tiles-albedo.png": 53.93040370941162,
91
- "port-40.avif": 1.7613801956176758,
92
- "saeukkang.usdz": 3.6647157669067383
93
- } as const;
337
+ // After (@d0paminedriven/fs)
338
+ fs.withWs('/path/to/dir/file.json', data);
94
339
  ```
95
- <small>ⓘ assets used were pooled from repos across github via the `fetchRemoteWriteLocalLargeFiles` method</small>
96
340
 
97
- <br>
341
+ ## 💡 Philosophy
342
+
343
+ This package embodies a simple philosophy: **filesystem operations should be atomic, safe, and obvious**.
344
+
345
+ - **Atomic**: Operations either fully succeed or fully fail
346
+ - **Safe**: No memory explosions, no race conditions
347
+ - **Obvious**: One method does one thing well
348
+
349
+ The `withWs` method is the crown jewel - it eliminates an entire category of bugs (missing directories) that plague every Node.js application. After using it for 3+ years, the creator literally forgot that "directory doesn't exist" errors were even a thing.
98
350
 
99
351
  ---
100
352
 
@@ -102,4 +354,10 @@ export const fileSizesInMb = {
102
354
  |:----:|:----:|:------:|
103
355
  | [![npm](https://img.shields.io/npm/v/@d0paminedriven/fs?color=blue)](https://www.npmjs.com/package/@d0paminedriven/fs) | [![npm](https://img.shields.io/npm/dm/@d0paminedriven/fs)](https://www.npmjs.com/package/@d0paminedriven/fs) | <a style="fill:white;" href="https://github.com/DopamineDriven/d0paminedriven/tree/master/packages/fs"><svg height="24" aria-hidden="true" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"><path d="M12 1C5.9225 1 1 5.9225 1 12C1 16.8675 4.14875 20.9787 8.52125 22.4362C9.07125 22.5325 9.2775 22.2025 9.2775 21.9137C9.2775 21.6525 9.26375 20.7862 9.26375 19.865C6.5 20.3737 5.785 19.1912 5.565 18.5725C5.44125 18.2562 4.905 17.28 4.4375 17.0187C4.0525 16.8125 3.5025 16.3037 4.42375 16.29C5.29 16.2762 5.90875 17.0875 6.115 17.4175C7.105 19.0812 8.68625 18.6137 9.31875 18.325C9.415 17.61 9.70375 17.1287 10.02 16.8537C7.5725 16.5787 5.015 15.63 5.015 11.4225C5.015 10.2262 5.44125 9.23625 6.1425 8.46625C6.0325 8.19125 5.6475 7.06375 6.2525 5.55125C6.2525 5.55125 7.17375 5.2625 9.2775 6.67875C10.1575 6.43125 11.0925 6.3075 12.0275 6.3075C12.9625 6.3075 13.8975 6.43125 14.7775 6.67875C16.8813 5.24875 17.8025 5.55125 17.8025 5.55125C18.4075 7.06375 18.0225 8.19125 17.9125 8.46625C18.6138 9.23625 19.04 10.2125 19.04 11.4225C19.04 15.6437 16.4688 16.5787 14.0213 16.8537C14.42 17.1975 14.7638 17.8575 14.7638 18.8887C14.7638 20.36 14.75 21.5425 14.75 21.9137C14.75 22.2025 14.9563 22.5462 15.5063 22.4362C19.8513 20.9787 23 16.8537 23 12C23 5.9225 18.0775 1 12 1Z"></path></svg></a>
104
356
 
357
+ ## 📜 License
358
+
359
+ MIT © [DopamineDriven](https://github.com/DopamineDriven)
360
+
105
361
  ---
362
+
363
+ **Built with frustration, refined with experience, shared with love.** 🚀