# Load a `.lottie` File
Learn how to load and read .lottie files using dotlottie-js from a URL or ArrayBuffer. Access animations, images, and manifest data.

# Load a `.lottie` File

This guide demonstrates how to load an existing `.lottie` file using `dotlottie-js` and access its contents, such as animations, images, and manifest data.

It primarily uses the `DotLottie` (V2) class. When loading a `.lottie` file, `dotlottie-js` automatically detects if it's a V1 or V2 format and handles it appropriately, typically by converting V1 to V2 internally for a consistent API experience.

## Prerequisites

Ensure you have `dotlottie-js` installed ([Installation](/docs/tools/dotlottie-js/how-to-guides/install)). You'll also need a `.lottie` file to test with. You can create one using the example in the [Creating Quick Start](/docs/tools/dotlottie-js/how-to-guides/create-and-export-a-lottie-file) guide, or use an existing one.

## Example: Loading from a URL (Browser)

In a browser environment, you can load a `.lottie` file directly from a URL.

```javascript
import { DotLottie } from "@dotlottie/dotlottie-js";

async function loadFromUrlAndRead(url) {
  try {
    // 1. Create a new DotLottie instance
    const dotlottie = await new DotLottie().fromURL(url);

    console.log("Successfully loaded .lottie from URL:", url);

    // 3. Access Manifest Data
    const manifest = dotlottie.manifest;
    if (manifest) {
      console.log("Manifest:", manifest);
      console.log("Version:", manifest.version);
      console.log("Generator:", manifest.generator);
      console.log("Author:", manifest.author);
      console.log("Initial Animation ID:", manifest.initial);
    }

    // 4. Access Animations
    const animations = dotlottie.animations;
    if (animations.length > 0) {
      console.log(`Found ${animations.length} animation(s):`);
      for (const anim of animations) {
        console.log(` - Animation ID: ${anim.id}, Name: ${anim.name}`);
        // You can get the animation data as a Lottie JSON object
        const animationData = await anim.toJSON();
        // console.log('   Animation JSON data:', animationData);
      }
    }

    // 5. Access Images (if any are bundled)
    const images = dotlottie.getImages();
    if (images.length > 0) {
      console.log(`Found ${images.length} image(s):`);
      images.forEach(async (img) => {
        console.log(` - Image ID: ${img.id}, File Name: ${img.fileName}`);
        // You can get the image data as a data URL
        // const dataURL = await img.toDataURL();
        // console.log('   Image Base64 Preview (first 50 chars):', dataURL.substring(0,50));
      });
    }

    // 6. Access Themes (V2 specific)
    const themes = dotlottie.themes;
    if (themes.length > 0) {
      console.log(`Found ${themes.length} theme(s):`);
      themes.forEach(async (theme) => {
        console.log(` - Theme ID: ${theme.id}, Name: ${theme.name}`);
        const themeData = theme.data;
        // console.log('   Theme data:', themeData);
      });
    }

    // 7. Access State Machines (V2 specific)
    const stateMachines = dotlottie.stateMachines;
    if (stateMachines.length > 0) {
      console.log(`Found ${stateMachines.length} state machine(s):`);
      stateMachines.forEach(async (sm) => {
        console.log(` - State Machine ID: ${sm.id}`);
        const smData = sm.toString();
        // console.log('   State Machine data:', smData);
      });
    }
  } catch (error) {
    console.error("Error loading or reading .lottie file from URL:", error);
  }
}

// Example usage:
// Replace with the URL of your .lottie file
// const dotLottieUrl = 'https://example.com/path/to/your/animation.lottie';
// const dotLottieUrl = 'https://lottie.host/4db68bbd-31f6-4cd8-84eb-189de081159a/IGmMCqhzpt.lottie'; // Example
// loadFromUrlAndRead(dotLottieUrl);
```

**Explanation:**

1. **`new DotLottie()`**: Instantiate the `DotLottie` class.
2. **`fromURL(url)`**: This asynchronous method fetches the `.lottie` file from the provided URL, unzips it, parses the `manifest.json`, and makes animations and assets available. Note that this method returns a **new instance** of DotLottie.
3. **`dotlottie.manifest`**: Accesses the parsed manifest object.
4. **`dotlottie.animations`**: An array where each item represents an animation. You can access properties like `id`, `name`, and use methods like `toJSON()` (async, returns the Lottie JSON object) on each item.
5. **`dotlottie.getImages()`**: Returns an array of items, where each item provides access to an image's `id`, `fileName`, and methods like `toDataURL()`.
6. **`dotlottie.themes`**: An array of `LottieTheme` instances (V2 only).
7. **`dotlottie.stateMachines`**: An array of `LottieStateMachine` instances (V2 only).

## Example: Loading from an ArrayBuffer (Node.js / Browser)

This method is useful in Node.js when you've read a file into a buffer, or in the browser if you've fetched a `.lottie` file as an `ArrayBuffer` (e.g., via `fetch` API or from a file input).

```javascript
// const fs = require('fs/promises');
import { DotLottie } from "@dotlottie/dotlottie-js"; // For browser

async function loadFromArrayBufferAndRead(arrayBuffer) {
  try {
    const dotlottie = new DotLottie().fromArrayBuffer(arrayBuffer);

    console.log("Successfully loaded .lottie from ArrayBuffer.");

    // Access data as shown in the fromURL example (manifest, animations, images, etc.)
    const manifest = dotlottie.manifest;
    if (manifest) console.log("Manifest generator:", manifest.generator);

    const animations = dotlottie.animations;
    if (animations.length > 0) {
      console.log(`First animation ID: ${animations[0].id}`);
      // const firstAnimData = await animations[0].toJSON();
      // console.log(firstAnimData);
    }
  } catch (error) {
    console.error("Error loading or reading .lottie file from ArrayBuffer:", error);
  }
}

// Example Usage (Browser - e.g., from a file input):
/*
document.getElementById('fileInput').addEventListener('change', async (event) => {
  const file = event.target.files[0];
  if (file) {
    const arrayBuffer = await file.arrayBuffer();
    loadFromArrayBufferAndRead(arrayBuffer);
  }
});
*/

// Example Usage (Node.js):
/*
async function mainNode() {
  try {
    const filePath = 'path/to/your/animation.lottie'; // Replace with your file path
    const fileBuffer = await fs.readFile(filePath);
    // In Node.js, fs.readFile returns a Buffer. Convert it to ArrayBuffer if needed,
    // though fromArrayBuffer might handle Node.js Buffers directly (check library specifics or test).
    // For safety, explicit conversion:
    const arrayBuffer = fileBuffer.buffer.slice(fileBuffer.byteOffset, fileBuffer.byteOffset + fileBuffer.byteLength);
    await loadFromArrayBufferAndRead(arrayBuffer);
  } catch (err) {
    console.error('Node.js example error:', err);
  }
}
mainNode();
*/
```

**Key Points for `fromArrayBuffer`:**

- **Input:** Takes an `ArrayBuffer` as an argument.
- **Node.js:** When reading files in Node.js using `fs.readFile`, you get a Node.js `Buffer`. You may need to convert this to an `ArrayBuffer` (e.g., using `nodeBuffer.buffer.slice(...)`).
- **Functionality:** Once loaded, accessing manifest, animations, and assets works the same way as shown in the `fromURL` example.

These examples provide a start for loading and inspecting `.lottie` files.

Next up: [Format Versions](/docs/tools/dotlottie-js/reference/format-versions)
