如何检查文件是否存在于反应中

问题描述 投票:0回答:3

我正在构建下一个 js React 网站,该网站从 api 获取音频文件并将它们存储在本地。但是,我想在调用 api 之前检查文件是否已经存在,以避免不必要的 api 调用。互联网上的大多数解决方案都是针对节点 js 环境的,但我正在寻找一种可以在客户端浏览器上运行的解决方案。

任何帮助将不胜感激。

javascript node.js reactjs next.js
3个回答
0
投票

如果你需要检查一个文件是否存在于 React 中,最好的方法是使用文件系统 API。此 API 允许您从 React 应用程序中读取和写入文件。要检查文件是否存在,可以使用 fs.existsSync() 方法,如果文件存在则返回 true,否则返回 false。在尝试访问该文件之前,您还应该确保您正在检查的路径有效。

检查文件是否存在的另一种方法是使用 Fetch API,它允许您发出 HTTP 请求以获取有关特定文件的信息。如果请求返回状态代码 200,则表示该文件存在。否则就代表不存在

最后,您还可以使用 Node 模块,例如“fs-extra”或“glob”,它们提供了额外的方法来检查 React 应用程序中是否存在文件。


0
投票

由于 next.js 是基于 node js 运行时的,所以你可以使用 fs 模块,特别是 existsSync

这是一种同步方法,可让您检查文件是否存在。


const fs = require('fs');
const path = './someFile.txt';

if (fs.existsSync(path)) {
  console.log('file exists');
} 

-2
投票

在客户端浏览器环境下,可以利用浏览器内置的Fetch API、本地存储等功能,在调用API前检查文件是否已经存在。这是您可以遵循的高级方法:

When you need to check if a file exists, first check the local storage if the file information is stored there.
If the file information is found in the local storage, it means the file already exists locally.
If the file information is not found in the local storage, make an API call to fetch the file from the server.
Upon receiving the file from the API response, store the file locally using the local storage for future reference.

这里有一个示例代码片段来演示这种方法:

javascript

// Function to check if a file exists locally
function checkFileLocally(fileName) {
  // Check if file information exists in local storage
  const fileData = localStorage.getItem(fileName);
  
  if (fileData) {
    // File exists locally
    return true;
  } else {
    // File does not exist locally
    return false;
  }
}

// Function to fetch and store a file
async function fetchAndStoreFile(fileName) {
  try {
    // Make API call to fetch the file
    const response = await fetch(`/api/files/${fileName}`);
    
    // Check if API call was successful
    if (response.ok) {
      // File fetched successfully
      const fileData = await response.blob();
      
      // Store file locally in local storage
      localStorage.setItem(fileName, fileData);
      
      // Use the file data as needed
      // ...
    } else {
      // Handle API error
      console.error('API error:', response.status);
    }
  } catch (error) {
    // Handle fetch error
    console.error('Fetch error:', error);
  }
}

// Example usage
const fileName = 'example.mp3';

if (checkFileLocally(fileName)) {
  // File exists locally, use it
  // ...
} else {
  // File does not exist locally, fetch and store it
  fetchAndStoreFile(fileName);
}

注意,这种方式将文件数据以字符串的形式存储在本地存储中。您可能需要根据文件格式以及您希望如何处理存储的数据来修改它。此外,请记住,本地存储对其可存储的数据量有限制,因此考虑您计划在本地存储的文件的大小和数量非常重要。

© www.soinside.com 2019 - 2024. All rights reserved.