DEV Community

Cover image for How to Get Total Video Length from a Zip Archive in Node.js
shivlal kumavat
shivlal kumavat

Posted on

How to Get Total Video Length from a Zip Archive in Node.js

Introduction

In this tutorial, we'll delve into the process of calculating the total duration of videos contained within a zip archive using Node.js. This can be particularly useful for media management, video editing, or any scenario where you need to quickly assess the total video footage in a compressed file.

Prerequisites:

Installation:

Node.js and npm (or yarn) installed on your system.

Create a new Node.js project:

mkdir video-duration-calculator
cd video-duration-calculator
npm init -y

Install required dependencies:

npm install unzipper get-video-duration path fs

Code Implementation index.ts:

import * as fs from "fs";
import { getVideoDurationInSeconds } from "get-video-duration";
import * as unzipper from "unzipper";
import * as path from "path";

async function calculateTotalDuration(zipFilePath: string): Promise<number> {
  try {
    let totalDurationSeconds = 0;

    const directory = await unzipper.Open.file(zipFilePath);

    for (const entry of directory.files) {
      if (entry.path.match(/\.(mp4|mov|avi|mkv)$/i)) {
        const videoData = await entry.buffer();

        // Construct the temporary file path (cross-platform compatible)
        const tempFilePath = `./temp_${entry.path.replace(/[/\\]/g, "_")}`;

        console.log("Entry name:", entry.path);
        console.log("Temporary file path:", tempFilePath);

        // Ensure the directory exists (cross-platform compatible)
        const dirName = tempFilePath.substring(
          0,
          tempFilePath.lastIndexOf(path.sep)
        );
        if (!fs.existsSync(dirName)) {
          fs.mkdirSync(dirName, { recursive: true });
        }

        fs.writeFileSync(tempFilePath, videoData);

        try {
          await new Promise((resolve) => setTimeout(resolve, 100));

          const duration = await getVideoDurationInSeconds(tempFilePath);
          totalDurationSeconds += duration;
        } catch (readError) {
          console.error(
            `Error reading video duration from ${tempFilePath}:`,
            readError
          );
        } finally {
          try {
            fs.unlinkSync(tempFilePath);
          } catch (deleteError) {
            console.error(
              `Error deleting temporary file ${tempFilePath}:`,
              deleteError
            );
          }
        }
      }
    }

    const totalDurationMinutes = totalDurationSeconds / 60;
    return parseFloat(totalDurationMinutes.toFixed(2));
  } catch (error) {
    console.error("Error calculating total duration:", error);
    throw error;
  }
}

// Example usage (adjust the path according to your OS)
const zipFilePath =
  process.platform === "win32"
    ? "C:\\Users\\your-username\\Downloads\\video-test-duretion.zip"
    : "/home/lcom/Documents/video-test-duretion.zip";

calculateTotalDuration(zipFilePath)
  .then((totalDurationMinutes) => {
    console.log(`Total duration of videos =>: ${totalDurationMinutes} minutes`);
  })
  .catch((error) => {
    console.error("Error:", error);
  });
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Unzipping: The code uses the unzipper library to extract the video files from the zip archive.
  • Temporary File Creation: Each extracted video is saved to a temporary file.
  • Video Duration Calculation: The get-video-duration library is used to calculate the duration of each temporary video file.
  • Total Duration Calculation: The total duration of all videos is calculated by summing up the individual durations.
  • Cleanup: Temporary files are deleted after processing.
  • Cross-Platform Compatibility:
  • The code is designed to work on both Windows and Linux systems by using the path.sep property to determine the correct file separator.

Remember to:

  • Replace the placeholder zipFilePath with the actual path to your zip file.
  • Install the required dependencies (unzipper and get-video-duration) using npm install.
  • Adjust the code and error handling as needed for your specific use case.
  • By following these steps and understanding the code's logic, you can effectively calculate the total video duration from a zip archive using Node.js.

Thank you for reading. For more blog https://dev.to/slk5611

Top comments (0)