WebExeBuilder Documentation

readFileAsBase64

Category: File Operations

Namespace: web.files.readFileAsBase64

Description

Reads a binary file from the local disk and returns its contents as a Base64-encoded string. Works with any file type — images, PDFs, audio, documents, or any other binary format.

Use this API whenever you need to load a binary file into memory. For plain text files, use readTextFile() instead.

Syntax

const base64 = await web.files.readFileAsBase64({
    filePath: string
});

Parameters

  • filePath (required) - Path to the file to read (relative or absolute)

Returns

Promise<string> - Base64-encoded contents of the file. Throws on error (file not found, access denied, etc.)

Examples

Display a local image

const base64 = await web.files.readFileAsBase64({
    filePath: 'C:\\Users\\Alice\\Pictures\\photo.jpg'
});

const img = document.getElementById('preview');
img.src = `data:image/jpeg;base64,${base64}`;

Load a PDF for PDF.js

const base64 = await web.files.readFileAsBase64({
    filePath: 'C:\\Documents\\report.pdf'
});

// atob() decodes Base64 to a binary string; Uint8Array converts to bytes
const binary = atob(base64);
const bytes  = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i);
}

const pdfDoc = await pdfjsLib.getDocument({ data: bytes.buffer }).promise;

Open a file via dialog then read it

const filePath = await web.dialogs.openFile({
    title:     'Open Image',
    fileTypes: 'Images|*.jpg;*.png;*.gif|All Files|*.*'
});

if (filePath) {
    try {
        const base64 = await web.files.readFileAsBase64({ filePath });
        const ext    = filePath.split('.').pop().toLowerCase();
        document.getElementById('img').src = `data:image/${ext};base64,${base64}`;
    } catch (error) {
        alert('Could not open file:\n' + error);
    }
}

Use Cases

  • Display local images (JPG, PNG, GIF, BMP, WebP, SVG) as data URLs
  • Load local PDFs into PDF.js or other binary-aware libraries
  • Read any binary file into memory for processing or transmission
  • Round-trip binary files with writeFileAsBase64()

When to Use

Use readFileAsBase64() when:

  • You need to read a binary file (images, PDFs, audio, etc.)
  • You want to display the file content in the browser (data URL)
  • You need to pass binary data to a JavaScript library

Use readTextFile() when:

  • The file is plain text (UTF-8), such as .txt, .json, .csv, .md

Use fetchToBase64() when:

  • The file is on a remote server (HTTP/HTTPS URL), not on the local disk

Notes

  • Relative paths are resolved from the application executable directory
  • Parent directories are not created — the file must already exist
  • Base64 encoding increases the in-memory size by approximately 33%
  • For very large files (>50 MB) consider whether loading entirely into memory is appropriate
  • Throws an error if the file does not exist or cannot be read