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.
Before we jump in, make sure you've got:
Got all that? Great! Let's get started.
First things first, let's get our package installed:
npm install @azure/storage-file-share
Easy peasy, right?
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);
async function createShare(shareName) { const shareClient = serviceClient.getShareClient(shareName); await shareClient.create(); console.log(`Share "${shareName}" created successfully!`); }
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!`); }
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!`); }
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); } }
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!`); }
async function createDirectory(shareName, dirName) { const shareClient = serviceClient.getShareClient(shareName); const dirClient = shareClient.getDirectoryClient(dirName); await dirClient.create(); console.log(`Directory "${dirName}" created successfully!`); }
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}"`); }
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}"`); }
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 } );
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!"); }
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);
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.