Sling Academy
Home/JavaScript/Organize Files and Folders with the JavaScript File and Directory Entries API

Organize Files and Folders with the JavaScript File and Directory Entries API

Last updated: December 12, 2024

The process of organizing files and folders on a user's machine has always been a somewhat manual process. However, with the advent of the JavaScript File and Directory Entries API, developers now have the ability to provide users with a convenient interface for handling files and directories directly from a web application.

The File and Directory Entries API allows web applications to interact with local file systems, making it possible to read, write, and organize files and directories without leaving the browser. The API is asynchronous, meaning it will not block the main thread, providing a smooth user experience even when dealing with large amounts of data. Below is a basic overview of how to use this API effectively.

Requesting File System Access

The first step is to request access to the file system. This is done using the window.showDirectoryPicker function, which prompts the user to select a directory. Here’s how you can use this function:

async function getDirectoryHandle() {
  const directoryHandle = await window.showDirectoryPicker();
  console.log(directoryHandle);
}

When the getDirectoryHandle function is called, it opens a system file picker that allows the user to select a directory. Once a directory is picked, it returns a directory handle that can be used for further operations such as reading and writing files.

Reading Files and Directories

Once you have a directory handle, you can iterate through its contents with the help of the for await...of loop. You can distinguish between files and directories and handle them accordingly:

async function listContents(directoryHandle) {
  for await (const entry of directoryHandle.values()) {
    console.log(entry.kind, entry.name);
    if (entry.kind === 'directory') {
      await listContents(entry); // Recursive call for nested directories
    }
  }
}

This function logs the type (file or directory) and the name of each entry to the console. For directories, it dives deeper recursively, which allows you to explore sub-folders.

Creating Files and Directories

After accessing a directory, you might want to create new files or directories within. This is straightforward with the API:

async function createFile(directoryHandle, fileName) {
  const newFileHandle = await directoryHandle.getFileHandle(fileName, { create: true });
  console.log('File created:', newFileHandle.name);
}

async function createDirectory(directoryHandle, directoryName) {
  const newDirHandle = await directoryHandle.getDirectoryHandle(directoryName, { create: true });
  console.log('Directory created:', newDirHandle.name);
}

The above example includes functions to create both a file and a directory. You must pass the second parameter as { create: true } to ensure that the selected file or directory is created if it doesn’t already exist.

Writing to Files

For writing data to a file, the API provides a writable stream:

async function writeFile(fileHandle, contents) {
  const writable = await fileHandle.createWritable();
  await writable.write(contents);
  await writable.close();
  console.log('File written successfully');
}

This function accepts a file handle and a string or buffer with the data you want to write. It then creates a writable stream and writes the data to the file.

Deleting Files and Directories

Deletion can Be performed by calling removeEntry on a directory handle, specifying the name of the file or directory you wish to delete:

async function deleteEntry(directoryHandle, entryName) {
  await directoryHandle.removeEntry(entryName);
  console.log('Entry deleted:', entryName);
}

With these basic operations, you can structure your own application to upload, read, write, and delete file system entries according to business or user needs. The ability to manage and organize file structures via the browser is a powerful feature that can lead to more dynamic and user-friendly web applications.

Next Article: Enter and Exit Fullscreen Mode Using the Fullscreen API in JavaScript

Previous Article: Enhance File Uploads with Directory Selections in JavaScript

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration