New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@azure/storage-file

Package Overview
Dependencies
Maintainers
4
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@azure/storage-file - npm Package Compare versions

Comparing version 10.1.0 to 12.0.0-preview.1

browser/azure-storage-file.min.js

31

BreakingChanges.md
# Breaking Changes
2018.01 Version 10.1.0
2019.07 Version 12.0.0-preview.1
* Updated convenience layer methods enum type parameters into typescript union types, this will help reducing bundle footprint.
* Updated URL encoding strategy for `url` parameters of `new XXXURL(url, pipeline)` methods, such as `new FileURL(url, pipeline)`.
* URL will accept both encoded or non-encoded URL string. It will escape non-escaped special characters, like Chinese characters. However, if directory/file name includes `%`, `url` must be encoded manually.
* `SASQueryParameters` is not going to be exported in browser bundle, and will be exported in Node.js runtime.
* IE11 needs `Array.prototype.includes` and `Object.keys` polyfills loaded.
- Client types are renamed from *URL to *Client.
- ServiceURL, ShareURL, DirectoryURL and FileURL to ServiceClient to FileServiceClient, ShareClient, DirectoryClient and FileClient respectively.
- Aborter parameters are now moved into option bags.
- `abortSignal` attrubute(optional) in the option-bag of respective module has to be utitlized for the `Aborter.timeout(<milliseconds>)` functionality.
- `Aborter.none` is the default value.
- I- prefixes are removed from interface names.
- Example- `IDirectoryCreateOptions` is updated to `DirectoryCreateOptions`, the new names have to be used.
- The static methods to create client types are removed. The functionality is moved into new instance methods added to the parent clients.
- The telemetry strings have been updated.
- `Azure-Storage/${SDK_VERSION}` is updated to `azsdk-js-storageblob/${SDK_VERSION}`.
- `withPipeline()` method is removed.
- Methods that list segments(`listFilesAndDirectoriesSegment()` and `listSharesSegment()`) are no longer exposed in public api.
- High level convenience functions are moved into clients as their instance member function.
- `uploadFileToAzureFile()`, `uploadStreamToAzureFile()`, `downloadAzureFileToBuffer()` and `uploadBrowserDataToAzureFile()` -> `FileClient.uploadFile()`,
`FileClient.uploadStream()`, `FileClient.downloadToBuffer()` and `FileClient.uploadBrowserData()` respectively.
- `StorageClient` is no longer exposed. `StorageClient.newPipeline()` static method is moved to the top level exported function `newPipeline()`.
2019.01 Version 10.1.0
- Updated convenience layer methods enum type parameters into typescript union types, this will help reducing bundle footprint.
- Updated URL encoding strategy for `url` parameters of `new XXXURL(url, pipeline)` methods, such as `new FileURL(url, pipeline)`.
- URL will accept both encoded or non-encoded URL string. It will escape non-escaped special characters, like Chinese characters. However, if directory/file name includes `%`, `url` must be encoded manually.
- `SASQueryParameters` is not going to be exported in browser bundle, and will be exported in Node.js runtime.
- IE11 needs `Array.prototype.includes` and `Object.keys` polyfills loaded.

@@ -0,0 +0,0 @@ ------------------------------------------- START OF THIRD PARTY NOTICE -----------------------------------------

59

ChangeLog.md
# Changelog
2018.01 Version 10.1.0
2019.07 Version 12.0.0-preview.1
* [Breaking] Updated convenience layer methods enum type parameters into typescript union types, this will help reducing bundle footprint.
* [Breaking] Updated URL encoding strategy for `url` parameters of `new XXXURL(url, pipeline)` methods, such as `new FileURL(url, pipeline)`.
* URL will accept both encoded or non-encoded URL string. It will escape non-escaped special characters, like Chinese characters. However, if directory/file name includes `%`, `url` must be encoded manually.
* [Breaking] `SASQueryParameters` is not going to be exported in browser bundle, and will be exported in Node.js runtime.
* [Breaking] IE11 needs `Array.prototype.includes` and `Object.keys` polyfills loaded.
* Updated dependency `ms-rest-js` to `@azure/ms-rest-js`.
* Fixed `Aborter.timeout()` misleading scale description.
* Removed default 60s server timeout value for retry options `tryTimeoutInMs` to avoid large blob download stream unexpected ending.
* Fixed an issue that when body is string with special characters, `FileURL.uploadRange` will fail to upload.
* Exported `HttpRequestBody` type for who wants to implement a customized HTTP client.
- [Breaking] Client types are renamed from *URL to *Client.
- ServiceURL, ShareURL, DirectoryURL and FileURL to FileServiceClient, ShareClient, DirectoryClient and FileClient respectively.
- [Breaking] Aborter parameters are now moved into option bags.
- `abortSignal` attrubute(optional) in the option-bag of respective module has to be utitlized for the `Aborter.timeout(<milliseconds>)` functionality.
- `Aborter.none` is the default value.
- [Breaking] I- prefixes are removed from interface names.
- Example- `IDirectoryCreateOptions` is updated to `DirectoryCreateOptions`, the new names must to be used.
- [Breaking] The static methods to create client types are removed. The functionality is moved into new instance methods added to the parent clients.
- [Breaking] The telemetry strings have been updated.
- `Azure-Storage/${SDK_VERSION}` is updated to `azsdk-js-storageblob/${SDK_VERSION}`.
- [Breaking] `withPipeline()` method is removed.
- Async iterators with pagination support are added for listing methods
- `listFilesAndDirectories()` and `listShares()`
- Please refer to the samples for async iterators in the `samples` folder.
- [Breaking] Methods that list segments(`listFilesAndDirectoriesSegment()` and `listSharesSegment()`) are no longer exposed in public api.
- [Breaking] High level convenience functions are moved into clients as their instance member function.
- `uploadFileToAzureFile()`, `uploadStreamToAzureFile()`, `downloadAzureFileToBuffer()` and `uploadBrowserDataToAzureFile()` -> `FileClient.uploadFile()`,
`FileClient.uploadStream()`, `FileClient.downloadToBuffer()` and `FileClient.uploadBrowserData()` respectively.
- [Breaking] `StorageClient` is no longer exposed. `StorageClient.newPipeline()` static method is moved to the top level exported function `newPipeline()`.
- Updated dependency `@azure/ms-rest-js` to `@azure/core-http`.
- Constructor overloads added into client types so they can be constructed from a url and a pipeline/credential and connection string.
- Constructors with overloads - `FileServiceClient` and `ShareClient`
- Connection string method is supported only in Node.js (not browsers).
- Creation/Deletion of child resources are duplicated to parent client type.
- HTTP proxy support is added (Node.js only).
- Please refer to the `proxyAuth.ts` sample in the `samples/typescript` folder.
- Request and response headers are now logged at INFO level, with sensitive data redacted.
- `downloadToFile()` is added to `FileClient`.
For release notes and more information please visit https://aka.ms/azure-sdk-preview1-js
2019.01 Version 10.1.0
- [Breaking] Updated convenience layer methods enum type parameters into typescript union types, this will help reducing bundle footprint.
- [Breaking] Updated URL encoding strategy for `url` parameters of `new XXXURL(url, pipeline)` methods, such as `new FileURL(url, pipeline)`.
- URL will accept both encoded or non-encoded URL string. It will escape non-escaped special characters, like Chinese characters. However, if directory/file name includes `%`, `url` must be encoded manually.
- [Breaking] `SASQueryParameters` is not going to be exported in browser bundle, and will be exported in Node.js runtime.
- [Breaking] IE11 needs `Array.prototype.includes` and `Object.keys` polyfills loaded.
- Updated dependency `ms-rest-js` to `@azure/ms-rest-js`.
- Fixed `Aborter.timeout()` misleading scale description.
- Removed default 60s server timeout value for retry options `tryTimeoutInMs` to avoid large blob download stream unexpected ending.
- Fixed an issue that when body is string with special characters, `FileURL.uploadRange` will fail to upload.
- Exported `HttpRequestBody` type for who wants to implement a customized HTTP client.
2018.12 Version 10.0.0-preview
* Initial Release. API version 2018-03-28 supported. Please see the README for information on the new design.
- Initial Release. API version 2018-03-28 supported. Please see the README for information on the new design.
{
"name": "@azure/storage-file",
"version": "10.1.0",
"sdk-type": "client",
"version": "12.0.0-preview.1",
"description": "Microsoft Azure Storage SDK for JavaScript - File",
"main": "./dist/index.js",
"module": "./dist-esm/lib/index.js",
"module": "./dist-esm/src/index.js",
"browser": {
"./dist/index.js": "./browser/azure-storage.file.min.js",
"./dist-esm/lib/index.js": "./dist-esm/lib/index.browser.js",
"./dist-esm/tests/utils/index.js": "./dist-esm/tests/utils/index.browser.js",
"./dist-esm/lib/FileDownloadResponse.js": "./dist-esm/lib/FileDownloadResponse.browser.js",
"./dist/index.js": "./browser/azure-storage-file.min.js",
"./dist-esm/src/index.js": "./dist-esm/src/index.browser.js",
"./dist-esm/src/credentials/SharedKeyCredential.js": "./dist-esm/src/credentials/SharedKeyCredential.browser.js",
"./dist-esm/test/utils/index.js": "./dist-esm/test/utils/index.browser.js",
"./dist-esm/src/FileDownloadResponse.js": "./dist-esm/src/FileDownloadResponse.browser.js",
"os": false,
"process": false
},
"types": "./typings/lib/index.d.ts",
"engines": {
"node": ">=6.5.0"
"types": "./typings/src/index.d.ts",
"engine": {
"node": ">=6.0.0"
},
"scripts": {
"audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit",
"build:autorest": "autorest ./swagger/README.md --typescript --use=@microsoft.azure/autorest.typescript@2.2.1",
"build:browserzip": "gulp zip",
"build:es6": "tsc -p tsconfig.json",
"build:nodebrowser": "rollup -c 2>&1",
"build:js-samples": "npm run clean && npm run build:es6 && cross-env ONLY_NODE=true rollup -c 2>&1",
"build:ts-samples": "npm run clean && cd samples && tsc -p . ",
"build:test": "npm run build:es6 && rollup -c rollup.test.config.js 2>&1",
"build": "npm run build:es6 && npm run build:nodebrowser && npm run build:browserzip",
"check-format": "prettier --list-different --config ../../.prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"",
"clean": "rimraf dist dist-esm dist-test typings temp browser/*.js* browser/*.zip statistics.html coverage coverage-browser .nyc_output *.tgz *.log test*.xml TEST*.xml",
"extract-api": "tsc -p . && api-extractor run --local",
"format": "prettier --write --config ../../.prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"",
"integration-test:browser": "karma start --single-run",
"integration-test:node": "nyc mocha --require source-map-support/register --reporter mocha-multi --reporter-options spec=-,mocha-junit-reporter=- --full-trace -t 120000 --retries 2 dist-test/index.node.js",
"integration-test": "npm run integration-test:node && npm run integration-test:browser",
"lint:fix": "eslint -c ../../.eslintrc.json src test samples --ext .ts --fix",
"lint": "eslint -c ../../.eslintrc.json src test samples --ext .ts -f node_modules/eslint-detailed-reporter/lib/detailed.js -o storage-file-lintReport.html || exit 0",
"pack": "npm pack 2>&1",
"prebuild": "npm run clean",
"test:browser": "npm run clean && npm run build:test && npm run integration-test:browser",
"test:node": "npm run clean && npm run build:test && npm run integration-test:node",
"test": "npm run clean && npm run build:test && npm run integration-test",
"unit-test:browser": "cross-env TEST_MODE=playback npm run integration-test:browser",
"unit-test:node": "cross-env TEST_MODE=playback npm run integration-test:node",
"unit-test": "npm run unit-test:node && npm run unit-test:browser"
},
"files": [
"BreakingChanges.md",
"browser/*.min.js*",
"browser/ThirdPartyNotices.txt",
"dist/",
"dist-esm/src/",
"LICENSE",
"src/",
"typings/src",
"tsconfig.json"
],
"repository": {
"type": "git",
"url": "git+https://github.com/Azure/azure-sdk-for-js.git"
},
"keywords": [
"Azure",
"Storage",
"File",
"Node.js",
"TypeScript",
"JavaScript",
"Browser"
],
"author": "Microsoft Corporation",
"license": "MIT",
"bugs": {
"url": "https://github.com/Azure/azure-sdk-for-js/issues"
},
"homepage": "https://github.com/Azure/azure-sdk-for-js#readme",
"sideEffects": false,
"dependencies": {
"events": "3.0.0",
"@azure/ms-rest-js": "1.2.6",
"@azure/core-http": "^1.0.0-preview.1",
"@azure/core-paging": "^1.0.0-preview.1",
"events": "^3.0.0",
"tslib": "^1.9.3"
},
"devDependencies": {
"@microsoft/api-extractor": "^7.1.5",
"@types/dotenv": "^6.1.0",
"@types/fs-extra": "~7.0.0",
"@types/mocha": "^5.2.5",
"@types/node": "^10.12.18",
"@types/nise": "^1.4.0",
"@types/nock": "^10.0.1",
"@types/node": "^8.0.0",
"@types/query-string": "6.2.0",
"@typescript-eslint/eslint-plugin": "^1.11.0",
"@typescript-eslint/parser": "^1.11.0",
"assert": "^1.4.1",
"cross-env": "^5.2.0",
"dotenv": "^7.0.0",
"es6-promise": "^4.2.5",
"eslint": "^5.16.0",
"eslint-config-prettier": "^4.2.0",
"eslint-detailed-reporter": "^0.8.0",
"eslint-plugin-no-null": "^1.0.2",
"eslint-plugin-no-only-tests": "^2.3.0",
"eslint-plugin-promise": "^4.1.1",
"fs-extra": "~8.0.1",
"gulp": "^4.0.0",
"gulp-zip": "^4.2.0",
"karma": "^3.1.1",
"inherits": "^2.0.3",
"karma": "^4.0.1",
"karma-chrome-launcher": "^2.2.0",

@@ -39,2 +118,4 @@ "karma-coverage": "^1.1.2",

"karma-ie-launcher": "^1.0.0",
"karma-json-preprocessor": "^0.3.3",
"karma-json-to-file-reporter": "^1.0.1",
"karma-junit-reporter": "^1.2.0",

@@ -46,10 +127,14 @@ "karma-mocha": "^1.3.0",

"mocha-junit-reporter": "^1.18.0",
"mocha-multi-reporters": "^1.1.7",
"nyc": "^13.1.0",
"mocha-multi": "^1.0.1",
"nise": "^1.4.10",
"nock": "^10.0.6",
"nyc": "^14.0.0",
"prettier": "^1.16.4",
"puppeteer": "^1.11.0",
"query-string": "^5.0.0",
"rimraf": "^2.6.2",
"rollup": "^1.0.0",
"rollup-plugin-commonjs": "^9.2.0",
"rollup": "~1.13.1",
"rollup-plugin-commonjs": "^10.0.0",
"rollup-plugin-multi-entry": "^2.1.0",
"rollup-plugin-node-resolve": "^4.0.0",
"rollup-plugin-node-resolve": "^5.0.2",
"rollup-plugin-replace": "^2.1.0",

@@ -59,39 +144,8 @@ "rollup-plugin-shim": "^1.0.0",

"rollup-plugin-uglify": "^6.0.0",
"rollup-plugin-visualizer": "^0.9.2",
"rollup-plugin-visualizer": "^1.0.0",
"source-map-support": "^0.5.9",
"ts-node": "^7.0.1",
"typescript": "^3.2.2"
},
"scripts": {
"test": "npm run test:node && npm run test:browser",
"test:node": "cross-env TS_NODE_COMPILER_OPTIONS=\"{\\\"module\\\": \\\"commonjs\\\"}\" nyc mocha --compilers ts-node/register --require source-map-support/register --reporter mocha-multi-reporters --reporter-options configFile=mocha.reporter.config.json --full-trace --no-timeouts tests/*.test.ts tests/node/*.test.ts",
"test:browser": "karma start --single-run",
"build": "npm run build:es6 && npm run build:nodebrowser && npm run build:browserzip && npm run build:test",
"build:test": "rollup -c rollup.test.config.js",
"build:nodebrowser": "rollup -c",
"build:es6": "tsc -p tsconfig.json",
"build:autorest": "autorest ./swagger/README.md --typescript --use=@microsoft.azure/autorest.typescript@2.2.1",
"build:browserzip": "gulp zip",
"clean": "rimraf dist dist-esm dist-test typings temp browser/*.js* browser/*.zip statistics.html coverage coverage-browser .nyc_output *.tgz *.log test*.xml TEST*.xml"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Azure/azure-storage-js.git"
},
"keywords": [
"Azure",
"Storage",
"File",
"Node.js",
"TypeScript",
"JavaScript",
"Browser"
],
"author": "Microsoft Corporation",
"license": "MIT",
"bugs": {
"url": "https://github.com/Azure/azure-storage-js/issues"
},
"homepage": "https://github.com/Azure/azure-storage-js#readme",
"sideEffects": false
"typescript": "^3.2.2",
"util": "^0.11.1"
}
}

@@ -1,27 +0,26 @@

# Azure Storage SDK V10 for JavaScript - File
# Azure Storage client library for JavaScript - File
* [![npm version](https://badge.fury.io/js/%40azure%2Fstorage-file.svg)](https://badge.fury.io/js/%40azure%2Fstorage-file)
* [API Reference documentation](https://docs.microsoft.com/en-us/javascript/api/%40azure/storage-file/index?view=azure-node-preview)
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.
## Introduction
This project provides a client library in JavaScript that makes it easy to consume Microsoft Azure File Storage service.
This project provides a SDK in JavaScript that makes it easy to consume Microsoft Azure Storage services.
[Source code](https://github.com/Azure/azure-sdk-for-js/tree/feature/storage/sdk/storage/storage-file) | [Package (npm)](https://www.npmjs.com/package/@azure/storage-file) | [API Reference Documentation](https://azure.github.io/azure-sdk-for-js/storage-file/index.html) | [Product documentation](https://docs.microsoft.com/en-us/azure/storage/files/storage-files-introduction) | [Samples](https://github.com/Azure/azure-sdk-for-js/tree/feature/storage/sdk/storage/storage-file/samples) | [Azure Storage File REST APIs](https://docs.microsoft.com/en-us/rest/api/storageservices/file-service-rest-api)
Please note that this version of the SDK is a compete overhaul of the current [Azure Storage SDK for Node.js and JavaScript in Browsers](https://github.com/azure/azure-storage-node), and is based on the new Storage SDK architecture.
## Key concepts
### Features
* File Storage
* Get/Set File Service Properties
* Create/List/Delete File Shares
* Create/List/Delete File Directories
* Create/Read/List/Update/Delete Files
* Features new
* Asynchronous I/O for all operations using the async methods
* HttpPipeline which enables a high degree of per-request configurability
* 1-to-1 correlation with the Storage REST API for clarity and simplicity
- File Storage
- Get/Set File Service Properties
- Create/List/Delete File Shares
- Create/List/Delete File Directories
- Create/Read/List/Update/Delete Files
- Features new
- Asynchronous I/O for all operations using the async methods
- HttpPipeline which enables a high degree of per-request configurability
- 1-to-1 correlation with the Storage REST API for clarity and simplicity
### Compatibility
This SDK is compatible with Node.js and browsers, and validated against LTS Node.js versions (>=6.5) and latest versions of Chrome, Firefox and Edge.
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.

@@ -31,42 +30,45 @@ #### Compatible with IE11

You need polyfills to make this library work with IE11. The easiest way is to use [@babel/polyfill](https://babeljs.io/docs/en/babel-polyfill), or [polyfill service](https://polyfill.io/v2/docs/).
Or you can load separate polyfills for missed ES feature(s).
You can also load separate polyfills for missed ES feature(s).
This library depends on following ES features which need external polyfills loaded.
* `Promise`
* `String.prototype.startsWith`
* `String.prototype.endsWith`
* `String.prototype.repeat`
* `String.prototype.includes`
* `Array.prototype.includes`
* `Object.keys` (Override IE11's `Object.keys` with ES6 polyfill forcely to enable [ES6 behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys#Notes))
- `Promise`
- `String.prototype.startsWith`
- `String.prototype.endsWith`
- `String.prototype.repeat`
- `String.prototype.includes`
- `Array.prototype.includes`
- `Object.keys` (Override IE11's `Object.keys` with ES6 polyfill forcely to enable [ES6 behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys#Notes))
- `Symbol`
#### Differences between Node.js and browsers
There are differences between Node.js and browsers runtime. When getting start with this SDK, pay attention to APIs or classes marked with _"ONLY AVAILABLE IN NODE.JS RUNTIME"_ or _"ONLY AVAILABLE IN 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
* Shared Key Authorization based on account name and account key
* `SharedKeyCredential`
* Shared Access Signature(SAS) generation
* `generateAccountSASQueryParameters()`
* `generateFileSASQueryParameters()`
* Parallel uploading and downloading
* `uploadFileToAzureFile()`
* `uploadStreamToAzureFile()`
* `downloadAzureFileToBuffer()`
- Shared Key Authorization based on account name and account key
- `SharedKeyCredential`
- Shared Access Signature(SAS) generation
- `generateAccountSASQueryParameters()`
- `generateFileSASQueryParameters()`
- Parallel uploading and downloading
- `FileClient.uploadFile()`
- `FileClient.uploadStream()`
- `FileClient.downloadToBuffer()`
- `FileClient.downloadToFile()`
##### Following features, interfaces, classes or functions are only available in browsers
* Parallel uploading and downloading
* `uploadBrowserDataToAzureFile()`
- Parallel uploading and downloading
- `FileClient.uploadBrowserData()`
## Getting Started
## Getting started
### NPM
The preferred way to install the Azure Storage SDK for JavaScript is to use the npm package manager. Simply type the following into a terminal window:
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:
```bash
npm install @azure/storage-file
npm install @azure/storage-file@12.0.0-preview.1
```

@@ -86,8 +88,8 @@

### JavaScript Bundle
### JavaScript bundle
To use the SDK with JS bundle in the browsers, simply add a script tag to your HTML pages pointing to the downloaded JS bundle file(s):
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):
```html
<script src="https://mydomain/azure-storage.file.min.js"></script>
<script src="https://mydomain/azure-storage-file.min.js"></script>
```

@@ -97,3 +99,3 @@

* `azfile`
- `azfile`

@@ -104,3 +106,3 @@ #### Download

* File [https://aka.ms/downloadazurestoragejsfile](https://aka.ms/downloadazurestoragejsfile)
- File [https://aka.ms/downloadazurestoragejsfile](https://aka.ms/downloadazurestoragejsfile)

@@ -113,128 +115,135 @@ ### CORS

* Allowed origins: \*
* Allowed verbs: DELETE,GET,HEAD,MERGE,POST,OPTIONS,PUT
* Allowed headers: \*
* Exposed headers: \*
* Maximum age (seconds): 86400
- Allowed origins: \*
- Allowed verbs: DELETE,GET,HEAD,MERGE,POST,OPTIONS,PUT
- Allowed headers: \*
- Exposed headers: \*
- Maximum age (seconds): 86400
## SDK Architecture
## Examples
The Azure Storage SDK for JavaScript provides low-level and high-level APIs.
### Create the file service client
* ServiceURL, ShareURL, DirectoryURL and FileURL objects provide the low-level API functionality and map one-to-one to the [Azure Storage File REST APIs](https://docs.microsoft.com/en-us/rest/api/storageservices/file-service-rest-api).
Use the constructor to create a instance of `FileServiceClient`, passing in the credential.
* The high-level APIs provide convenience abstractions such as uploading a large stream to a file (using multiple PutBlock requests).
```javascript
// Enter your storage account name and shared key
const account = "";
const accountKey = "";
## Code Samples
// Use SharedKeyCredential with storage account and account key
// SharedKeyCredential is only avaiable in Node.js runtime, not in browsers
const sharedKeyCredential = new SharedKeyCredential(account, accountKey);
const serviceClient = new FileServiceClient(
// When using AnonymousCredential, following url should include a valid SAS
`https://${account}.file.core.windows.net`,
sharedKeyCredential
);
```
```javascript
const {
Aborter,
StorageURL,
ServiceURL,
ShareURL,
DirectoryURL,
FileURL,
SharedKeyCredential,
AnonymousCredential
} = require("@azure/storage-file");
### List shares in the account
async function main() {
// Enter your storage account name and shared key
const account = "";
const accountKey = "";
Use `ShareServiceClient.listShares()` to iterator shares in this account,
with the new `for-await-of` syntax:
// Use SharedKeyCredential with storage account and account key
// SharedKeyCredential is only avaiable in Node.js runtime, not in browsers
const sharedKeyCredential = new SharedKeyCredential(account, accountKey);
```javascript
let shareIter1 = serviceClient.listShares();
let i = 1;
for await (const share of shareIter1) {
console.log(`Share${i}: ${share.name}`);
i++;
}
```
// Use AnonymousCredential when url already includes a SAS signature
const anonymousCredential = new AnonymousCredential();
Alternatively without `for-await-of`:
// Use sharedKeyCredential or anonymousCredential to create a pipeline
const pipeline = StorageURL.newPipeline(sharedKeyCredential);
```javascript
let shareIter2 = await serviceClient.listShares();
i = 1;
let shareItem = await shareIter2.next();
while (!shareItem.done) {
console.log(`Share${i++}: ${shareItem.value.name}`);
shareItem = await shareIter2.next();
}
```
// List shares
const serviceURL = new ServiceURL(
// When using AnonymousCredential, following url should include a valid SAS
`https://${account}.file.core.windows.net`,
pipeline
);
### Create a new share and a directory
console.log(`List shares`);
let marker;
do {
const listSharesResponse = await serviceURL.listSharesSegment(
Aborter.none,
marker
);
```javascript
const shareName = `newshare${new Date().getTime()}`;
const shareClient = serviceClient.getShareClient(shareName);
await shareClient.create();
console.log(`Create share ${shareName} successfully`);
marker = listSharesResponse.nextMarker;
for (const share of listSharesResponse.shareItems) {
console.log(`\tShare: ${share.name}`);
}
} while (marker);
const directoryName = `newdirectory${new Date().getTime()}`;
const directoryClient = shareClient.getDirectoryClient(directoryName);
await directoryClient.create();
console.log(`Create directory ${directoryName} successfully`);
```
// Create a share
const shareName = `newshare${new Date().getTime()}`;
const shareURL = ShareURL.fromServiceURL(serviceURL, shareName);
await shareURL.create(Aborter.none);
console.log(`Create share ${shareName} successfully`);
### Create an azure file then upload to it
// Create a directory
const directoryName = `newdirectory${new Date().getTime()}`;
const directoryURL = DirectoryURL.fromShareURL(shareURL, directoryName);
await directoryURL.create(Aborter.none);
console.log(`Create directory ${directoryName} successfully`);
```javascript
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`);
// Create a file
const content = "Hello World!";
const fileName = "newfile" + new Date().getTime();
const fileURL = FileURL.fromDirectoryURL(directoryURL, fileName);
await fileURL.create(Aborter.none, 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`);
```
// Upload file range
await fileURL.uploadRange(Aborter.none, content, 0, content.length);
console.log(`Upload file range "${content}" to ${fileName} successfully`);
### List files and directories under a directory
// List directories and files
console.log(`List directories and files under directory ${directoryName}`);
marker = undefined;
do {
const listFilesAndDirectoriesResponse = await directoryURL.listFilesAndDirectoriesSegment(
Aborter.none,
marker
);
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.
marker = listFilesAndDirectoriesResponse.nextMarker;
for (const file of listFilesAndDirectoriesResponse.segment.fileItems) {
console.log(`\tFile: ${file.name}`);
```javascript
let dirIter1 = directoryClient.listFilesAndDirectories();
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}`);
}
for (const directory of listFilesAndDirectoriesResponse.segment
.directoryItems) {
console.log(`\tDirectory: ${directory.name}`);
}
} while (marker);
i++;
}
```
// Get file content from position 0 to the end
// In Node.js, get downloaded data by accessing downloadFileResponse.readableStreamBody
// In browsers, get downloaded data by accessing downloadFileResponse.blobBody
const downloadFileResponse = await fileURL.download(Aborter.none, 0);
console.log(
`Downloaded file content${await streamToString(
downloadFileResponse.readableStreamBody
)}`
);
Alternatively without using `for-await-of`:
// Delete share
await shareURL.delete(Aborter.none);
console.log(`deleted share ${shareName}`);
```javascript
let dirIter2 = await directoryClient.listFilesAndDirectories();
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();
}
```
// A helper method used to read a Node.js readable stream into string
For a complete sample on iterating blobs please see [samples/iterators-files-and-directories.ts](https://github.com/Azure/azure-sdk-for-js/blob/feature/storage/sdk/storage/storage-file/samples/typescript/iterators-files-and-directories.ts).
### Download a file and convert it to a string (Node.js)
```javascript
// Get file content from position 0 to the end
// In Node.js, get downloaded data by accessing downloadFileResponse.readableStreamBody
const downloadFileResponse = await fileClient.download(0);
console.log(
`Downloaded file content${await streamToString(downloadFileResponse.readableStreamBody)}`
);
// [Node.js only] A helper method used to read a Node.js readable stream into string
async function streamToString(readableStream) {
return new Promise((resolve, reject) => {
const chunks = [];
readableStream.on("data", data => {
readableStream.on("data", (data) => {
chunks.push(data.toString());

@@ -248,22 +257,76 @@ });

}
```
// An async method returns a Promise object, which is compatible with then().catch() coding style.
main()
.then(() => {
console.log("Successfully executed sample.");
})
.catch(err => {
console.log(err.message);
### Download a file and convert it to a string (Browsers)
```javascript
// 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 streamToString(
downloadFileResponse.blobBody
)}`
);
// [Browser only] A helper method used to convert a browser Blob into string.
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);
});
}
```
## More Code Samples
A complete example of basic scenarios is at [samples/basic.ts](https://github.com/Azure/azure-sdk-for-js/blob/feature/storage/sdk/storage/storage-file/samples/typescript/basic.ts).
* [File Storage Examples](https://github.com/azure/azure-storage-js/tree/master/file/samples)
* [File Storage Examples - Test Cases](https://github.com/azure/azure-storage-js/tree/master/file/test/)
## Troubleshooting
## License
It could help diagnozing issues by turning on the console logging. Here's an example logger implementation. First, add a custom logger:
This project is licensed under MIT.
```javascript
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;
}
}
}
```
When creating the `FileServiceClient` instance, pass the logger in the options
```javascript
const fileServiceClient = new FileServiceClient(
`https://${account}.file.core.windows.net`,
sharedKeyCredential,
{
logger: new ConsoleHttpPipelineLogger(HttpPipelineLogLevel.INFO)
}
);
```
## Next steps
More code samples
- [File Storage Examples](https://github.com/Azure/azure-sdk-for-js/tree/feature/storage/sdk/storage/storage-file/samples)
- [File Storage Examples - Test Cases](https://github.com/Azure/azure-sdk-for-js/tree/feature/storage/sdk/storage/storage-file/test)
## Contributing

@@ -270,0 +333,0 @@

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc