Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
@azure/storage-file-share
Advanced tools
@azure/storage-file-share is an Azure SDK package that allows developers to interact with Azure File Storage. It provides functionalities to manage file shares, directories, and files in Azure Storage accounts.
Create a File Share
This feature allows you to create a new file share in your Azure Storage account. The code sample demonstrates how to use the ShareServiceClient to create a file share named 'my-new-share'.
const { ShareServiceClient } = require('@azure/storage-file-share');
const connectionString = 'Your_Connection_String';
const serviceClient = ShareServiceClient.fromConnectionString(connectionString);
async function createShare() {
const shareName = 'my-new-share';
const shareClient = serviceClient.getShareClient(shareName);
await shareClient.create();
console.log(`Share created: ${shareName}`);
}
createShare();
Upload a File
This feature allows you to upload a file to a specified file share and directory. The code sample shows how to upload a text file named 'example.txt' with the content 'Hello, Azure!' to the root directory of 'my-new-share'.
const { ShareServiceClient } = require('@azure/storage-file-share');
const fs = require('fs');
const connectionString = 'Your_Connection_String';
const serviceClient = ShareServiceClient.fromConnectionString(connectionString);
async function uploadFile() {
const shareName = 'my-new-share';
const directoryName = '';
const fileName = 'example.txt';
const fileContent = 'Hello, Azure!';
const shareClient = serviceClient.getShareClient(shareName);
const directoryClient = shareClient.getDirectoryClient(directoryName);
const fileClient = directoryClient.getFileClient(fileName);
await fileClient.create(fileContent.length);
await fileClient.uploadRange(fileContent, 0, fileContent.length);
console.log(`File uploaded: ${fileName}`);
}
uploadFile();
List Files and Directories
This feature allows you to list all files and directories within a specified directory of a file share. The code sample demonstrates how to list entities in the root directory of 'my-new-share'.
const { ShareServiceClient } = require('@azure/storage-file-share');
const connectionString = 'Your_Connection_String';
const serviceClient = ShareServiceClient.fromConnectionString(connectionString);
async function listFilesAndDirectories() {
const shareName = 'my-new-share';
const directoryName = '';
const shareClient = serviceClient.getShareClient(shareName);
const directoryClient = shareClient.getDirectoryClient(directoryName);
let iter = directoryClient.listFilesAndDirectories();
let entity = await iter.next();
while (!entity.done) {
console.log(`Entity: ${entity.value.name}`);
entity = await iter.next();
}
}
listFilesAndDirectories();
The aws-sdk package is the official AWS SDK for JavaScript, which provides similar functionalities for managing files in Amazon S3, a cloud storage service by AWS. While @azure/storage-file-share is specific to Azure File Storage, aws-sdk offers a broader range of services beyond just file storage, including S3, DynamoDB, and more.
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.
Use the client libraries in this package to:
Note: This package was previously published under the name
@azure/storage-file
. It has been renamed to@azure/storage-file-share
to better align with the upcoming new package for Azure Storage Files DataLake and provide a consistent set of APIs for working with files on Azure.
Key links:
See our support policy for more details.
The preferred way to install the Azure File Storage client library for JavaScript is to use the npm package manager. Type the following into a terminal window:
npm install @azure/storage-file-share
Azure Storage supports several ways to authenticate. In order to interact with the Azure Storage File Share service you'll need to create an instance of a Storage client - ShareServiceClient
, ShareClient
, or ShareDirectoryClient
for example. See samples for creating the ShareServiceClient
to learn more about authentication.
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.
This library requires certain DOM objects to be globally available when used in the browser, which web workers do not make available by default. You will need to polyfill these to make this library work in web workers.
For more information please refer to our documentation for using Azure SDK for JS in Web Workers
This library depends on following DOM APIs which need external polyfills loaded when used in web workers:
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".
gzip
or deflate
format and its content encoding is set accordingly, downloading behavior is different between Node.js and browsers. In Node.js storage clients will download the file in its compressed format, while in browsers the data will be downloaded in de-compressed format.StorageSharedKeyCredential
generateAccountSASQueryParameters()
generateFileSASQueryParameters()
ShareFileClient.uploadData()
is available in both Node.js and browsers.
ShareFileClient.uploadFile()
ShareFileClient.uploadStream()
ShareFileClient.downloadToBuffer()
ShareFileClient.downloadToFile()
N/A
To use this client library in the browser, first you need to use a bundler. For details on how to do this, please refer to our bundling documentation.
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.
The following components and their corresponding client libraries make up the Azure Storage File Share service:
ShareServiceClient
ShareClient
ShareDirectoryClient
instancesShareFileClient
To use the clients, import the package into your file:
const AzureStorageFileShare = require("@azure/storage-file-share");
Alternative, selectively import only the types you need:
const { ShareServiceClient, StorageSharedKeyCredential } = require("@azure/storage-file-share");
The ShareServiceClient
requires an URL to the file share service and an access credential. It also optionally accepts some settings in the options
parameter.
Alternatively, you can instantiate a ShareServiceClient
using the fromConnectionString()
static method with the full connection string as the argument. (The connection string can be obtained from the azure portal.)
const { ShareServiceClient } = require("@azure/storage-file-share");
const connStr = "<connection string>";
const shareServiceClient = ShareServiceClient.fromConnectionString(connStr);
StorageSharedKeyCredential
Pass in a StorageSharedKeyCredential
with your account name and account key. (The account-name and account-key can be obtained from the azure portal.)
const { ShareServiceClient, StorageSharedKeyCredential } = require("@azure/storage-file-share");
// Enter your storage account name and shared key
const account = "<account>";
const accountKey = "<accountkey>";
// Use StorageSharedKeyCredential with storage account and account key
// StorageSharedKeyCredential is only available in Node.js runtime, not in browsers
const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
// When using AnonymousCredential, following url should include a valid SAS
`https://${account}.file.core.windows.net`,
credential
);
Also, You can instantiate a ShareServiceClient
with a shared access signatures (SAS). You can get the SAS token from the Azure Portal or generate one using generateAccountSASQueryParameters()
.
const { ShareServiceClient } = require("@azure/storage-file-share");
const account = "<account name>";
const sas = "<service Shared Access Signature Token>";
const serviceClientWithSAS = new ShareServiceClient(
`https://${account}.file.core.windows.net${sas}`
);
Use ShareServiceClient.listShares()
to iterator shares in this account,
with the new for-await-of
syntax:
const { ShareServiceClient, StorageSharedKeyCredential } = require("@azure/storage-file-share");
const account = "<account>";
const accountKey = "<accountkey>";
const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
`https://${account}.file.core.windows.net`,
credential
);
async function main() {
const shareIter = serviceClient.listShares();
let i = 1;
for await (const share of shareIter) {
console.log(`Share${i}: ${share.name}`);
i++;
}
}
main();
Alternatively without for-await-of
:
const { ShareServiceClient, StorageSharedKeyCredential } = require("@azure/storage-file-share");
const account = "<account>";
const accountKey = "<accountkey>";
const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
`https://${account}.file.core.windows.net`,
credential
);
async function main() {
const shareIter = serviceClient.listShares();
let i = 1;
let shareItem = await shareIter.next();
while (!shareItem.done) {
console.log(`Share ${i++}: ${shareItem.value.name}`);
shareItem = await shareIter.next();
}
}
main();
const { ShareServiceClient, StorageSharedKeyCredential } = require("@azure/storage-file-share");
const account = "<account>";
const accountKey = "<accountkey>";
const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
`https://${account}.file.core.windows.net`,
credential
);
async function main() {
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`);
}
main();
const { ShareServiceClient, StorageSharedKeyCredential } = require("@azure/storage-file-share");
const account = "<account>";
const accountKey = "<accountkey>";
const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
`https://${account}.file.core.windows.net`,
credential
);
const shareName = "<share name>";
const directoryName = "<directory name>";
async function main() {
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);
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`);
// Upload file range
await fileClient.uploadRange(content, 0, content.length);
console.log(`Upload file range "${content}" to ${fileName} successfully`);
}
main();
Use DirectoryClient.listFilesAndDirectories()
to iterator over files and directories,
with the new for-await-of
syntax. The kind
property can be used to identify whether
a iterm is a directory or a file.
const { ShareServiceClient, StorageSharedKeyCredential } = require("@azure/storage-file-share");
const account = "<account>";
const accountKey = "<accountkey>";
const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
`https://${account}.file.core.windows.net`,
credential
);
const shareName = "<share name>";
const directoryName = "<directory name>";
async function main() {
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);
const dirIter = directoryClient.listFilesAndDirectories();
let i = 1;
for await (const item of dirIter) {
if (item.kind === "directory") {
console.log(`${i} - directory\t: ${item.name}`);
} else {
console.log(`${i} - file\t: ${item.name}`);
}
i++;
}
}
main();
Alternatively without using for-await-of
:
const { ShareServiceClient, StorageSharedKeyCredential } = require("@azure/storage-file-share");
const account = "<account>";
const accountKey = "<accountkey>";
const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
`https://${account}.file.core.windows.net`,
credential
);
const shareName = "<share name>";
const directoryName = "<directory name>";
async function main() {
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);
const dirIter = directoryClient.listFilesAndDirectories();
let i = 1;
let item = await dirIter.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}`);
}
i++;
item = await dirIter.next();
}
}
main();
For a complete sample on iterating please see samples/v12/typescript/src/listFilesAndDirectories.ts.
const { ShareServiceClient, StorageSharedKeyCredential } = require("@azure/storage-file-share");
const account = "<account>";
const accountKey = "<accountkey>";
const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
`https://${account}.file.core.windows.net`,
credential
);
const shareName = "<share name>";
const fileName = "<file name>";
// [Node.js only] A helper method used to read a Node.js readable stream into a Buffer
async function streamToBuffer(readableStream) {
return new Promise((resolve, reject) => {
const chunks = [];
readableStream.on("data", (data) => {
chunks.push(data instanceof Buffer ? data : Buffer.from(data));
});
readableStream.on("end", () => {
resolve(Buffer.concat(chunks));
});
readableStream.on("error", reject);
});
}
async function main() {
const fileClient = serviceClient
.getShareClient(shareName)
.rootDirectoryClient.getFileClient(fileName);
// Get file content from position 0 to the end
// In Node.js, get downloaded data by accessing downloadFileResponse.readableStreamBody
const downloadFileResponse = await fileClient.download();
console.log(
`Downloaded file content: ${(
await streamToBuffer(downloadFileResponse.readableStreamBody)
).toString()}`
);
}
main();
Please refer to the JavaScript Bundle section for more information on using this library in the browser.
const { ShareServiceClient } = require("@azure/storage-file-share");
const account = "<account name>";
const sas = "<service Shared Access Signature Token>";
const shareName = "<share name>";
const fileName = "<file name>";
const serviceClient = new ShareServiceClient(`https://${account}.file.core.windows.net${sas}`);
async function main() {
const fileClient = serviceClient
.getShareClient(shareName)
.rootDirectoryClient.getFileClient(fileName);
// Get file content from position 0 to the end
// In browsers, get downloaded data by accessing downloadFileResponse.blobBody
const downloadFileResponse = await fileClient.download(0);
console.log(
`Downloaded file content: ${await blobToString(await downloadFileResponse.blobBody)}`
);
}
// [Browser only] A helper method used to convert a browser Blob into string.
async function blobToString(blob) {
const fileReader = new FileReader();
return new Promise((resolve, reject) => {
fileReader.onloadend = (ev) => {
resolve(ev.target.result);
};
fileReader.onerror = reject;
fileReader.readAsText(blob);
});
}
main();
A complete example of simple ShareServiceClient
scenarios is at samples/v12/typescript/src/shareSerivceClient.ts.
Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the AZURE_LOG_LEVEL
environment variable to info
. Alternatively, logging can be enabled at runtime by calling setLogLevel
in the @azure/logger
:
const { setLogLevel } = require("@azure/logger");
setLogLevel("info");
More code samples
If you'd like to contribute to this library, please read the contributing guide to learn more about how to build and test the code.
Also refer to Storage specific guide for additional information on setting up the test environment for storage libraries.
FAQs
Microsoft Azure Storage SDK for JavaScript - File
We found that @azure/storage-file-share demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.