@azure/storage-file-share

Publish date: 2024-06-18

Azure Files offers fully managed file shares in the cloud that are accessible via the industry standard Server Message Block (SMB) protocol. Azure file shares can be mounted concurrently by cloud or on-premises deployments of Windows, Linux, and macOS. Additionally, Azure file shares can be cached on Windows Servers with Azure File Sync for fast access near where the data is being used.

This project provides a client library in JavaScript that makes it easy to consume Microsoft Azure File Storage service.

Version: 12.0.0-preview.5

Key concepts

Features

Compatibility

This library is compatible with Node.js and browsers, and validated against LTS Node.js versions (>=8.16.0) and latest versions of Chrome, Firefox and Edge.

Compatible with IE11

You need polyfills to make this library work with IE11. The easiest way is to use @babel/polyfill, or polyfill service.

You can also load separate polyfills for missed ES feature(s).This library depends on following ES features which need external polyfills loaded.

Differences between Node.js and browsers

There are differences between Node.js and browsers runtime. When getting started with this library, pay attention to APIs or classes marked with "ONLY AVAILABLE IN NODE.JS RUNTIME" or "ONLY AVAILABLE IN BROWSERS".

Following features, interfaces, classes or functions are only available in Node.js
Following features, interfaces, classes or functions are only available in browsers

Getting started

NPM

The preferred way to install the Azure File Storage client library for JavaScript is to use the npm package manager. Simply type the following into a terminal window:

npm install @azure/storage-file-share@12.0.0-preview.5

In your TypeScript or JavaScript file, import via following:

import * as AzureStorageFileShare from "@azure/storage-file-share";

Or

const AzureStorageFileShare = require("@azure/storage-file-share");

JavaScript bundle

To use the library with JS bundle in the browsers, simply add a script tag to your HTML pages pointing to the downloaded JS bundle file(s):

<script src="https://mydomain/azure-storage-file-share.min.js"></script>

The JS bundled file is compatible with UMD standard, if no module system found, following global variable(s) will be exported:

Download

Download latest released JS bundles from links in the GitHub release page.

CORS

You need to set up Cross-Origin Resource Sharing (CORS) rules for your storage account if you need to develop for browsers. Go to Azure portal and Azure Storage Explorer, find your storage account, create new CORS rules for blob/queue/file/table service(s).

For example, you can create following CORS settings for debugging. But please customize the settings carefully according to your requirements in production environment.

Examples

Import types

You can use the const Azure = require("@azure/storage-file-share"); shown above then use types and functions from Azure.Or you can selectively import certain types,

const { FileServiceClient, SharedKeyCredential } = require("@azure/storage-file-share"); );

Create the file service client

Use the constructor to create a instance of FileServiceClient, passing in the credential.

 const account = ""; const accountKey = ""; const sharedKeyCredential = new SharedKeyCredential(account, accountKey); const serviceClient = new FileServiceClient( `https://${account}.file.core.windows.net`, sharedKeyCredential );

List shares in the account

Use ShareServiceClient.listShares() to iterator shares in this account,with the new for-await-of syntax:

let shareIter1 = serviceClient.listShares(); let i = 1; for await (const share of shareIter1) { console.log(`Share${i}: ${share.name}`); i++; }

Alternatively without for-await-of:

let shareIter2 = await serviceClient.listShares(); let i = 1; let shareItem = await shareIter2.next(); while (!shareItem.done) { console.log(`Share ${i++}: ${shareItem.value.name}`); shareItem = await shareIter2.next(); }

Create a new share and a directory

const shareName = `newshare${new Date().getTime()}`; const shareClient = serviceClient.getShareClient(shareName); await shareClient.create(); console.log(`Create share ${shareName} successfully`); const directoryName = `newdirectory${new Date().getTime()}`; const directoryClient = shareClient.getDirectoryClient(directoryName); await directoryClient.create(); console.log(`Create directory ${directoryName} successfully`);

Create an azure file then upload to it

const content = "Hello World!"; const fileName = "newfile" + new Date().getTime(); const fileClient = directoryClient.getFileClient(fileName); await fileClient.create(content.length); console.log(`Create file ${fileName} successfully`); await fileClient.uploadRange(content, 0, content.length); console.log(`Upload file range "${content}" to ${fileName} successfully`);

List files and directories under a directory

Use DirectoryClient.listFilesAndDirectories() to iterator over files and directories,with the new for-await-of syntax. The kind property can be used to identify whethera iterm is a directory or a file.

let dirIter1 = directoryClient.listFilesAndDirectories(); let i = 1; for await (const item of dirIter1) { if (item.kind === "directory") { console.log(`${i} - directory\t: ${item.name}`); } else { console.log(`${i} - file\t: ${item.name}`); } i++; }

Alternatively without using for-await-of:

let dirIter2 = await directoryClient.listFilesAndDirectories(); let i = 1; let item = await dirIter2.next(); while (!item.done) { if (item.value.kind === "directory") { console.log(`${i} - directory\t: ${item.value.name}`); } else { console.log(`${i} - file\t: ${item.value.name}`); } item = await dirIter2.next(); }

For a complete sample on iterating please see samples/iterators-files-and-directories.ts.

Download a file and convert it to a string (Node.js)

 const downloadFileResponse = await fileClient.download(); console.log( `Downloaded file content: ${await streamToString(downloadFileResponse.readableStreamBody)}` ); async function streamToString(readableStream) { return new Promise((resolve, reject) => { const chunks = []; readableStream.on("data", (data) => { chunks.push(data.toString()); }); readableStream.on("end", () => { resolve(chunks.join("")); }); readableStream.on("error", reject); }); }

Download a file and convert it to a string (Browsers)

 const downloadFileResponse = await fileClient.download(0); console.log( `Downloaded file content: ${await streamToString( downloadFileResponse.blobBody )}` ); export async function blobToString(blob: Blob): Promise<string> { const fileReader = new FileReader(); return new Promise<string>((resolve, reject) => { fileReader.onloadend = (ev: any) => { resolve(ev.target!.result); }; fileReader.onerror = reject; fileReader.readAsText(blob); }); }

A complete example of basic scenarios is at samples/basic.ts.

Troubleshooting

It could help diagnozing issues by turning on the console logging. Here's an example logger implementation. First, add a custom logger:

class ConsoleHttpPipelineLogger { constructor(minimumLogLevel) { this.minimumLogLevel = minimumLogLevel; } log(logLevel, message) { const logMessage = `${new Date().toISOString()} ${HttpPipelineLogLevel[logLevel]}: ${message}`; switch (logLevel) { case HttpPipelineLogLevel.ERROR: console.error(logMessage); break; case HttpPipelineLogLevel.WARNING: console.warn(logMessage); break; case HttpPipelineLogLevel.INFO: console.log(logMessage); break; } } }

Then when creating the FileServiceClient instance, pass the logger in the options

const fileServiceClient = new FileServiceClient( `https://${account}.file.core.windows.net`, sharedKeyCredential, { logger: new ConsoleHttpPipelineLogger(HttpPipelineLogLevel.INFO) } );

Next steps

More code samples

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to aContributor License Agreement (CLA) declaring that you have the right to, and actually do, grant usthe rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to providea CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructionsprovided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct.For more information see the Code of Conduct FAQ orcontact opencode@microsoft.com with any additional questions or comments.

ncG1vNJzZmiZqqq%2Fpr%2FDpJuom6Njr627wWeaqKqVY8SqusOorqxmnprBcHDWnploopGrrrSv0aKnrWeRr8KzsYysq6iqkZyybrLIpZxmq5iWv6Z7kGtlaWZgYr2zsdWinLBmZWS2r7DEsWWhrJ2h