You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron/Angular应用访问文件夹视频技术问题咨询

Hey there! Let's work through the issues in your current code and get your video file loading working smoothly. I notice a few key areas that need tweaking, especially around async handling, path safety, and filtering video files. Here's how to fix it:

Key Issues in Your Current Code

  1. this Context Loss: The callback for fs.stat doesn't preserve your component's this context, which would cause problems if you tried to update this.nodes inside that callback.
  2. Uncontrolled Async Flow: fs.stat is asynchronous, so your console.log(this.nodes) runs before any of the stat callbacks complete—meaning you're logging an incomplete list.
  3. Unsafe Path Concatenation: Manually adding / to join paths breaks on Windows (which uses \).
  4. No Video Filtering: You're adding all files/folders to this.nodes, but you only want video files.

Improved Solution with Async/Await

Let's rewrite the code using promise-based fs methods and async/await to make it cleaner, safer, and more predictable:

// Import promise-based fs and path modules
import * as fs from 'fs/promises';
import * as path from 'path';

// Inside your Angular component
async loadVideoFiles() {
  try {
    // Read the directory contents
    const items = await fs.readdir(this.path);

    // Define video extensions you want to include (add more if needed)
    const allowedVideoExtensions = ['.mp4', '.avi', '.mov', '.mkv', '.flv', '.webm'];

    // Create async promises for each item to check if it's a video file
    const videoFilePromises = items.map(async (item) => {
      const fullFilePath = path.join(this.path, item);
      const fileStats = await fs.stat(fullFilePath);

      // Only keep files (skip folders) that match video extensions
      if (fileStats.isFile()) {
        const fileExt = path.extname(fullFilePath).toLowerCase();
        if (allowedVideoExtensions.includes(fileExt)) {
          return {
            source: fullFilePath,
            size: fileStats.size,
            fileName: item
          };
        }
      }
      return null; // Filter out non-video items later
    });

    // Wait for all promises to resolve, then filter out null values
    const validVideoNodes = (await Promise.all(videoFilePromises)).filter(node => node !== null);
    
    // Update your nodes array once all data is ready
    this.nodes = validVideoNodes;
    console.log('Successfully loaded video files:', this.nodes);

    // Now you can safely run any follow-up logic (like rendering the video list)
  } catch (error) {
    console.error('Failed to load video files:', error);
    // Add user-friendly error handling here, e.g., show a toast message
  }
}

Additional Tips

  • Recursive Folder Traversal: If you need to scan subfolders too, you can add a recursive check inside the map function—just call loadVideoFiles again on subfolder paths (be careful to avoid infinite loops!).
  • Electron Security: Make sure your Electron app's nodeIntegration and contextIsolation settings are configured correctly (since you're using angular-electron, this is probably handled, but double-check to avoid security risks).
  • Performance for Large Folders: If you're dealing with hundreds of video files, consider processing them in batches instead of all at once to avoid overwhelming the main thread.

内容的提问来源于stack exchange,提问作者Mel Pacheco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:50:03