Back

Step by Step Guide to Building an Azure Files API Integration in JS

Aug 7, 20246 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of Azure Files API integration? We'll be using the @azure/storage-file-share package to make our lives easier. This guide assumes you're already familiar with the basics, so we'll keep things snappy and focus on the good stuff.

Prerequisites

Before we jump in, make sure you've got:

  • A Node.js environment up and running
  • An Azure account with a storage account set up
  • Your connection string or SAS token handy

Got all that? Great! Let's get started.

Installation

First things first, let's get our package installed:

npm install @azure/storage-file-share

Easy peasy, right?

Authentication

Now, let's authenticate and create a ShareServiceClient:

const { ShareServiceClient } = require("@azure/storage-file-share"); const connectionString = "your_connection_string_here"; const serviceClient = ShareServiceClient.fromConnectionString(connectionString);

Basic Operations

Creating a file share

async function createShare(shareName) { const shareClient = serviceClient.getShareClient(shareName); await shareClient.create(); console.log(`Share "${shareName}" created successfully!`); }

Uploading a file

async function uploadFile(shareName, fileName, filePath) { const shareClient = serviceClient.getShareClient(shareName); const fileClient = shareClient.rootDirectoryClient.getFileClient(fileName); await fileClient.uploadFile(filePath); console.log(`File "${fileName}" uploaded successfully!`); }

Downloading a file

async function downloadFile(shareName, fileName, downloadPath) { const shareClient = serviceClient.getShareClient(shareName); const fileClient = shareClient.rootDirectoryClient.getFileClient(fileName); await fileClient.downloadToFile(downloadPath); console.log(`File "${fileName}" downloaded successfully!`); }

Listing files and directories

async function listFilesAndDirs(shareName) { const shareClient = serviceClient.getShareClient(shareName); let dirIter = shareClient.rootDirectoryClient.listFilesAndDirectories(); for await (const item of dirIter) { console.log(item.name, item.kind); } }

Deleting a file

async function deleteFile(shareName, fileName) { const shareClient = serviceClient.getShareClient(shareName); const fileClient = shareClient.rootDirectoryClient.getFileClient(fileName); await fileClient.deleteIfExists(); console.log(`File "${fileName}" deleted successfully!`); }

Advanced Operations

Working with directories

async function createDirectory(shareName, dirName) { const shareClient = serviceClient.getShareClient(shareName); const dirClient = shareClient.getDirectoryClient(dirName); await dirClient.create(); console.log(`Directory "${dirName}" created successfully!`); }

Managing file metadata

async function setFileMetadata(shareName, fileName, metadata) { const shareClient = serviceClient.getShareClient(shareName); const fileClient = shareClient.rootDirectoryClient.getFileClient(fileName); await fileClient.setMetadata(metadata); console.log(`Metadata set for file "${fileName}"`); }

Setting file properties

async function setFileProperties(shareName, fileName, properties) { const shareClient = serviceClient.getShareClient(shareName); const fileClient = shareClient.rootDirectoryClient.getFileClient(fileName); await fileClient.setProperties(properties); console.log(`Properties set for file "${fileName}"`); }

Error Handling and Best Practices

Always wrap your Azure operations in try-catch blocks:

try { await uploadFile(shareName, fileName, filePath); } catch (error) { console.error("Error uploading file:", error.message); }

Implement retry logic for transient errors:

const { DefaultAzureCredential } = require("@azure/identity"); const { StorageRetryPolicyType } = require("@azure/storage-file-share"); const credential = new DefaultAzureCredential(); const serviceClient = new ShareServiceClient( "https://<account>.file.core.windows.net", credential, { retryOptions: { maxTries: 4, tryTimeoutInMs: 10000 }, retryPolicyType: StorageRetryPolicyType.EXPONENTIAL } );

Performance Optimization

For better performance, use parallel operations when working with multiple files:

async function uploadMultipleFiles(shareName, files) { const shareClient = serviceClient.getShareClient(shareName); await Promise.all(files.map(file => shareClient.rootDirectoryClient.getFileClient(file.name).uploadFile(file.path) )); console.log("All files uploaded successfully!"); }

Security Considerations

Use Shared Access Signatures (SAS) for granular access control:

const { generateAccountSASQueryParameters, AccountSASPermissions, AccountSASResourceTypes, AccountSASServices } = require("@azure/storage-file-share"); const sasToken = generateAccountSASQueryParameters({ expiresOn: new Date(new Date().valueOf() + 86400), permissions: AccountSASPermissions.parse("rwdlc"), resourceTypes: AccountSASResourceTypes.parse("sco").toString(), services: AccountSASServices.parse("f").toString() }, "accountKey").toString(); console.log("SAS Token:", sasToken);

Conclusion

And there you have it! You're now equipped to integrate Azure Files API into your JS projects like a pro. Remember, practice makes perfect, so don't be afraid to experiment and push the boundaries. Happy coding!

For more in-depth information, check out the official Azure Storage documentation and the @azure/storage-file-share package documentation.