Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 6 min read

Building an In-Browser Bulk Folder & Batch Converter with Dynamic Extension Mapping and Client-Zip

Batch file conversion is a daily workflow for developers, designers, and photographers. Yet almost every online converter follows a broken pattern: Slow Network Uploads: To convert 50 images or 20 audio tracks, you mu

Batch file conversion is a daily workflow for developers, designers, and photographers. Yet almost every online converter follows a broken pattern:

  1. Slow Network Uploads: To convert 50 images or 20 audio tracks, you must first upload hundreds of megabytes over your home internet connection to a remote cloud server.
  2. Flattened Folder Structures: If your folder has nested subdirectories (e.g. assets/icons/ and assets/banners/), cloud converters strip the hierarchy and dump every converted file into a single messy root folder.
  3. One-Size-Fits-All Inflexibility: If your dropped folder contains mixed formats (say, 15 PNGs, 10 JPGs, and 5 SVGs), cloud tools force you to select a single target format for everything or reject the upload.
  4. Privacy & Egress Bills: Uploading private media to third-party servers creates privacy risks, while server operators pass heavy bandwidth and cloud compute costs down to you via subscriptions or rate limits.

For Fileo, we built a batch converter that runs 100% inside the browserβ€”offering recursive folder ingestion, mixed-format extension mapping, and instant ZIP downloads with zero server roundtrips.

Here is how we engineered it.

πŸ›οΈ High-Level Architecture

The in-browser batch pipeline executes four distinct stages entirely in client memory:

[User Drops Folder or Selects Directory]
                   β”‚
                   β–Ό
  [Recursive FileSystem Scanner]
  β”œβ”€ Resolves relative path tree (assets/sub/photo.png)
  └─ Auto-indexes unique extensions (.png, .jpg, .heic)
                   β”‚
                   β–Ό
  [Dynamic Extension Mapping Matrix]
  β”œβ”€ Group 1: 14 PNGs ──► Map to WebP (Quality: 80%)
  β”œβ”€ Group 2:  8 JPGs ──► Map to SVG (Vectorizing)
  └─ Group 3: 10 HEICs ──► Map to JPG (Quality: 95%)
                   β”‚
                   β–Ό
  [Sequential Worker Loop (with Event-Loop Yielding)]
  β”œβ”€ Converts file in client memory
  β”œβ”€ Updates real-time 60 FPS progress tickers
  └─ Pushes converted stream with original relative path
                   β”‚
                   β–Ό
  [client-zip Hierarchy-Preserving Stream]
  └─ Packages `${folderName}-converted.zip` (Instant download)

1. Dual-Mode Recursive Directory Ingestion

Browsers handle folder selection through two distinct mechanisms: native file picker dialogs and drag-and-drop. We built a unified pipeline supporting both.

Mode A: HTML5 Directory Input Picker

For direct button clicks, modern Chromium, Firefox, and Safari support the webkitdirectory attribute on file inputs:

<input
  type="file"
  id="folderInput"
  webkitdirectory
  directory
  multiple
  class="hidden"
/>

When a user selects a directory through this input, each File object exposes a webkitRelativePath property (e.g. "project/assets/logo.png").

Mode B: Drag-and-Drop Recursive Directory Traversal

When users drag and drop a folder directly into the browser viewport, event.dataTransfer.files only provides shallow file entries. To recursively read nested directories of arbitrary depth, we leverage the webkitGetAsEntry() API:

/**
 * Recursively scans directories and files from a DataTransferItem.
 */
async function traverseFileSystemEntry(
  entry: any,
  path = ''
): Promise<{ file: File; relativePath: string }[]> {
  if (!entry) return [];

  if (entry.isFile) {
    return new Promise((resolve) => {
      entry.file((file: File) => {
        resolve([{
          file,
          relativePath: path ? `${path}/${file.name}` : file.name
        }]);
      });
    });
  }

  if (entry.isDirectory) {
    const reader = entry.createReader();
    const entries: any[] = await new Promise((resolve) => {
      // readEntries reads up to 100 items per call; production requires batching loops
      reader.readEntries((results: any[]) => resolve(results));
    });

    const currentPath = path ? `${path}/${entry.name}` : entry.name;
    const subFiles = await Promise.all(
      entries.map((child) => traverseFileSystemEntry(child, currentPath))
    );
    return subFiles.flat();
  }

  return [];
}

2. The Dynamic Extension Mapping Matrix

Real-world project folders rarely contain just one file type. A typical web asset folder might contain 20 PNG screenshots, 10 JPG photos, and 5 SVG logos.

Instead of forcing a single uniform output, our engine dynamically inspects the batch, groups files by their unique extensions, and renders a Dynamic Extension Mapping UI:

interface ExtensionGroup {
  extension: string;
  count: number;
  files: { file: File; relativePath: string }[];
  targetFormat: string;
  quality: number;
}

// Automatically bucket ingested files into unique extension groups
function groupFilesByExtension(files: { file: File; relativePath: string }[]) {
  const groups: Record<string, ExtensionGroup> = {};

  for (const item of files) {
    const ext = item.file.name.split('.').pop()?.toLowerCase() || 'unknown';
    if (!groups[ext]) {
      groups[ext] = {
        extension: ext,
        count: 0,
        files: [],
        targetFormat: getDefaultTargetFor(ext),
        quality: 80,
      };
    }
    groups[ext].count++;
    groups[ext].files.push(item);
  }

  return Object.values(groups);
}

UI Capabilities:

  • Per-Extension Target Selection: Map .png files to .webp while simultaneously mapping .wav audio to .mp3 in the exact same batch.
  • Global One-Click Presets: Quick action buttons allow instant bulk configuration:
    • "All Images β†’ Modern WebP"
    • "All Images β†’ Vector SVG"
    • "All Media β†’ High-Fidelity MP3"
  • Quality Presets: Each group can be assigned custom compression levels: High (95%), Medium (80%), or Compact (60%).

3. 60 FPS Event-Loop Yielding Execution

The biggest danger of client-side batch processing is freezing the browser tab. If you loop through 100 images and encode them synchronously, the JavaScript main thread locks up, animations freeze, and the browser displays a "Page Unresponsive" dialog.

To keep the UI smooth at a flawless 60 FPS, we implemented sequential async batching with microtask event-loop yielding:

async function processBatchQueue(
  queue: ConversionTask[],
  onProgress: (current: number, total: number, fileName: string) => void
) {
  const convertedResults = [];

  for (let i = 0; i < queue.length; i++) {
    const task = queue[i];

    // 1. Update UI progress ticker
    onProgress(i + 1, queue.length, task.file.name);

    // 2. Execute in-memory conversion (Canvas / Web Audio / WASM)
    const convertedBlob = await executeConversion(task.file, task.targetFormat, task.quality);

    // 3. Compute output relative path preserving directory structure
    const outputRelativePath = task.relativePath.replace(
      /\.[^/.]+$/,
      `.${task.targetFormat}`
    );

    convertedResults.push({
      name: outputRelativePath,
      input: convertedBlob,
      lastModified: new Date(),
    });

    // 4. Critical: Yield back to browser event loop
    // Allows DOM paint, badge updates, and cancel click handlers
    await new Promise((resolve) => setTimeout(resolve, 0));
  }

  return convertedResults;
}

By yielding to the event loop (setTimeout(..., 0)) between conversions, the browser has ample time to update the progress bar, recalculate estimated time remaining, and paint smooth gradient animations.

4. Hierarchy-Preserving ZIP Streaming with client-zip

Once all files are converted in browser memory, how do we package them into a downloadable archive without crashing memory?

Traditional libraries like JSZip often allocate the entire uncompressed and compressed archive simultaneously in JavaScript heap memory, leading to out-of-memory crashes on batches larger than 100MB.

Instead, we integrated client-zip, a lightweight zero-dependency library that streams ZIP archives directly into a single Blob:

import { downloadZip } from 'client-zip';

async function packageConvertedFolder(
  convertedFiles: { name: string; input: Blob; lastModified: Date }[],
  originalFolderName: string
) {
  // client-zip receives relative paths and builds standard ZIP directory headers
  const zipBlob = await downloadZip(convertedFiles).blob();

  // Create immediate client-side download link
  const downloadUrl = URL.createObjectURL(zipBlob);
  const link = document.createElement('a');
  link.href = downloadUrl;
  link.download = `${originalFolderName || 'fileo'}-converted.zip`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  // Revoke URL to reclaim browser memory
  setTimeout(() => URL.revokeObjectURL(downloadUrl), 10000);
}

When the user unzips the downloaded archive, their operating system (macOS Finder, Windows Explorer, Linux) automatically re-creates the exact original nested folders (assets/icons/, photos/2026/), but with every file converted to their chosen formats.

πŸ“Š Comparison: Cloud Batch vs. Fileo In-Browser Engine

Metric Traditional Cloud Converter Fileo In-Browser Batch Engine
Upload Time Slow (Uploading full files over network) Instant (Zero upload, reads directly from disk)
Folder Hierarchy ❌ Flattened into single folder βœ… 100% Preserved nested subfolders
Mixed File Formats ❌ Uniform single target only βœ… Dynamic per-extension target mapping
File Size Ceilings Capped at 50MB–100MB (Paywalls) Limited only by local device RAM
Data Privacy Files stored on third-party servers 100% Private (Files never leave device)
Server Bandwidth Costs Expensive compute & egress bills $0.00 / month (Runs entirely on client)

πŸ’‘ Key Engineering Takeaways

  1. webkitdirectory + webkitGetAsEntry() is a Powerful Combo: Supporting both picker dialogs and recursive drag-and-drop provides the most intuitive file ingestion UX for web tools.
  2. Always Yield During Long Loops: Never perform heavy client-side batch conversions in a tight synchronous loop. A simple await new Promise(r => setTimeout(r, 0)) keeps your application running at 60 FPS.
  3. Use client-zip for Safe Client Archiving: Passing relative path strings into client-zip eliminates server zip-generation bottlenecks and guarantees flawless folder preservation.
  4. Client-Side Architecture Wins on Economics: Handling bulk conversions in the user's browser turns zero-server costs into a permanent competitive moat.

Links & Live Demo

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.