如何在nodejs中获取AWS共享路径中文件夹中的所有文件?

nhhxz33t  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(405)

我需要在AWS fsx中获取一个目录下的所有文件,我已经知道如何使用FS npm模块从特定目录中获取文件,但不知道如何从AWS Fsx获取。
我读了这份文件,但不知道或什么方法需要使用这一点。
文档:https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-fsx/ Npm:https://www.npmjs.com/package/@aws-sdk/client-fsx
我尝试了多个文件,但没有得到正确的方法使用。

tvmytwxo

tvmytwxo1#

我有一些你可以使用的示例节点代码。它使用aws-sdk@v2,所以如果你在v3 SDK上做过研发,它会有所不同。

const AWS = require('aws-sdk');

// Set your AWS credentials and region
AWS.config.update({
  accessKeyId: 'YOUR_ACCESS_KEY_ID',
  secretAccessKey: 'YOUR_SECRET_ACCESS_KEY',
  region: 'us-east-1' // Replace with your desired AWS region
});

// Create an AWS FSx for Windows File Server client
const fsxClient = new AWS.FSx();

// Specify the FSx directory ID and path
const directoryId = 'fs-xxxxxxxx';
const directoryPath = '\\SharedFolder\\Subfolder'; // Replace with your FSx directory path

// Recursive function to retrieve all files under a directory
async function getAllFiles(directoryId, directoryPath) {
  try {
    const listItemsParams = {
      DirectoryId: directoryId,
      Path: directoryPath
    };

    const listItemsResponse = await fsxClient.listItems(listItemsParams).promise();
    const files = listItemsResponse.Items.filter(item => item.Type === 'FILE');

    for (const file of files) {
      console.log(`File: ${file.Name}`);
    }

    const directories = listItemsResponse.Items.filter(item => item.Type === 'DIRECTORY');

    for (const directory of directories) {
      const subdirectoryPath = `${directoryPath}\\${directory.Name}`;
      await getAllFiles(directoryId, subdirectoryPath);
    }
  } catch (err) {
    console.error('Error retrieving files:', err);
  }
}

// Call the function to get all files under the directory
getAllFiles(directoryId, directoryPath);

相关问题