|
| 1 | +--- |
| 2 | +title: "Quickstart: Azure Blob storage library - TypeScript" |
| 3 | +description: In this quickstart, you learn how to use the Azure Blob Storage for TypeScript to create a container and a blob in Blob (object) storage. Next, you learn how to download the blob to your local computer, and how to list all of the blobs in a container. |
| 4 | +author: pauljewellmsft |
| 5 | +ms.author: pauljewell |
| 6 | +ms.date: 03/18/2024 |
| 7 | +ms.service: azure-blob-storage |
| 8 | +ms.topic: quickstart |
| 9 | +ms.devlang: typescript |
| 10 | +ms.custom: devx-track-js, mode-api, passwordless-js, devx-track-extended-azdevcli |
| 11 | +--- |
| 12 | + |
| 13 | +# Quickstart: Azure Blob Storage client library for Node.js with TypeScript |
| 14 | + |
| 15 | +Get started with the Azure Blob Storage client library for Node.js with TypeScript to manage blobs and containers. |
| 16 | + |
| 17 | +In this article, you follow steps to install the package and try out example code for basic tasks. |
| 18 | + |
| 19 | +[API reference](/javascript/api/@azure/storage-blob) | |
| 20 | +[Library source code](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/storage/storage-blob) | [Package (npm)](https://www.npmjs.com/package/@azure/storage-blob) | [Samples](../common/storage-samples-javascript.md?toc=/azure/storage/blobs/toc.json#blob-samples) |
| 21 | + |
| 22 | +## Prerequisites |
| 23 | + |
| 24 | +- Azure account with an active subscription - [create an account for free](https://azure.microsoft.com/free/?ref=microsoft.com&utm_source=microsoft.com&utm_medium=docs&utm_campaign=visualstudio) |
| 25 | +- Azure Storage account - [Create a storage account](../common/storage-account-create.md) |
| 26 | +- [Node.js LTS](https://nodejs.org/en/download/) |
| 27 | +- [TypeScript](https://www.typescriptlang.org/download) |
| 28 | + |
| 29 | +## Setting up |
| 30 | + |
| 31 | +This section walks you through preparing a project to work with the Azure Blob Storage client library for Node.js. |
| 32 | + |
| 33 | +### Create the Node.js project |
| 34 | + |
| 35 | +Create a TypeScript application named *blob-quickstart*. |
| 36 | + |
| 37 | +1. In a console window (such as cmd, PowerShell, or Bash), create a new directory for the project: |
| 38 | + |
| 39 | + ```console |
| 40 | + mkdir blob-quickstart |
| 41 | + ``` |
| 42 | + |
| 43 | +1. Switch to the newly created *blob-quickstart* directory: |
| 44 | + |
| 45 | + ```console |
| 46 | + cd blob-quickstart |
| 47 | + ``` |
| 48 | + |
| 49 | +1. Create a *package.json* file: |
| 50 | + |
| 51 | + ```console |
| 52 | + npm init -y |
| 53 | + ``` |
| 54 | + |
| 55 | +1. Open the project in Visual Studio Code: |
| 56 | + |
| 57 | + ```console |
| 58 | + code . |
| 59 | + ``` |
| 60 | + |
| 61 | +1. Edit the *package.json* file to add the following properties to support ESM with TypeScript: |
| 62 | + |
| 63 | + ```json |
| 64 | + "type": "module", |
| 65 | + ``` |
| 66 | + |
| 67 | +### Install the packages |
| 68 | + |
| 69 | +From the project directory, install the following packages using the `npm install` command. |
| 70 | + |
| 71 | +1. Install the Azure Storage npm package: |
| 72 | + |
| 73 | + ```console |
| 74 | + npm install @azure/storage-blob |
| 75 | + ``` |
| 76 | + |
| 77 | +1. Install other dependencies used in this quickstart: |
| 78 | + |
| 79 | + ```console |
| 80 | + npm install uuid dotenv @types/node @types/uuid |
| 81 | + ``` |
| 82 | + |
| 83 | + |
| 84 | +1. Create a `tsconfig.json` file in the project directory with the following contents. |
| 85 | + |
| 86 | + :::code language="json" source="~/azure_storage-snippets/blobs/quickstarts/TypeScript/V12/nodejs/tsconfig.json"::: |
| 87 | + |
| 88 | + |
| 89 | +## Object model |
| 90 | + |
| 91 | +Azure Blob storage is optimized for storing massive amounts of unstructured data. Unstructured data is data that doesn't adhere to a particular data model or definition, such as text or binary data. Blob storage offers three types of resources: |
| 92 | + |
| 93 | +- The storage account |
| 94 | +- A container in the storage account |
| 95 | +- A blob in the container |
| 96 | + |
| 97 | +The following diagram shows the relationship between these resources. |
| 98 | + |
| 99 | + |
| 100 | + |
| 101 | +Use the following JavaScript classes to interact with these resources: |
| 102 | + |
| 103 | +- [BlobServiceClient](/javascript/api/@azure/storage-blob/blobserviceclient): The `BlobServiceClient` class allows you to manipulate Azure Storage resources and blob containers. |
| 104 | +- [ContainerClient](/javascript/api/@azure/storage-blob/containerclient): The `ContainerClient` class allows you to manipulate Azure Storage containers and their blobs. |
| 105 | +- [BlobClient](/javascript/api/@azure/storage-blob/blobclient): The `BlobClient` class allows you to manipulate Azure Storage blobs. |
| 106 | + |
| 107 | +## Code examples |
| 108 | + |
| 109 | +These example code snippets show you how to do the following tasks with the Azure Blob Storage client library for JavaScript: |
| 110 | + |
| 111 | +- [Authenticate to Azure and authorize access to blob data](#authenticate-to-azure-and-authorize-access-to-blob-data) |
| 112 | +- [Create a container](#create-a-container) |
| 113 | +- [Upload blobs to a container](#upload-blobs-to-a-container) |
| 114 | +- [List the blobs in a container](#list-the-blobs-in-a-container) |
| 115 | +- [Download blobs](#download-blobs) |
| 116 | +- [Delete a container](#delete-a-container) |
| 117 | + |
| 118 | +Sample code is also available on [GitHub](https://github.com/Azure-Samples/AzureStorageSnippets/tree/master/blobs/quickstarts/JavaScript/V12/nodejs). |
| 119 | + |
| 120 | +### Authenticate to Azure and authorize access to blob data |
| 121 | + |
| 122 | +[!INCLUDE [storage-quickstart-passwordless-auth-intro](../../../includes/storage-quickstart-passwordless-auth-intro.md)] |
| 123 | + |
| 124 | +### [Passwordless (Recommended)](#tab/managed-identity) |
| 125 | + |
| 126 | +`DefaultAzureCredential` supports multiple authentication methods and determines which method should be used at runtime. This approach enables your app to use different authentication methods in different environments (local vs. production) without implementing environment-specific code. |
| 127 | + |
| 128 | +The order and locations in which `DefaultAzureCredential` looks for credentials can be found in the [Azure Identity library overview](/javascript/api/overview/azure/identity-readme#defaultazurecredential). |
| 129 | + |
| 130 | +For example, your app can authenticate using your Azure CLI sign-in credentials with when developing locally. Your app can then use a [managed identity](../../active-directory/managed-identities-azure-resources/overview.md) once it's deployed to Azure. No code changes are required for this transition. |
| 131 | + |
| 132 | +<a name='assign-roles-to-your-azure-ad-user-account'></a> |
| 133 | + |
| 134 | +#### Assign roles to your Microsoft Entra user account |
| 135 | + |
| 136 | +[!INCLUDE [assign-roles](../../../includes/assign-roles.md)] |
| 137 | + |
| 138 | +#### Sign in and connect your app code to Azure using DefaultAzureCredential |
| 139 | + |
| 140 | +You can authorize access to data in your storage account using the following steps: |
| 141 | + |
| 142 | +1. Make sure you're authenticated with the same Microsoft Entra account you assigned the role to on your storage account. You can authenticate via the Azure CLI, Visual Studio Code, or Azure PowerShell. |
| 143 | + |
| 144 | + #### [Azure CLI](#tab/sign-in-azure-cli) |
| 145 | + |
| 146 | + Sign-in to Azure through the Azure CLI using the following command: |
| 147 | + |
| 148 | + ```azurecli |
| 149 | + az login |
| 150 | + ``` |
| 151 | + |
| 152 | + #### [Visual Studio Code](#tab/sign-in-visual-studio-code) |
| 153 | + |
| 154 | + [Install the Azure CLI](/cli/azure/install-azure-cli) to work with `DefaultAzureCredential` through Visual Studio Code. |
| 155 | + |
| 156 | + On the main menu of Visual Studio Code, navigate to **Terminal > New Terminal**. |
| 157 | + |
| 158 | + Sign-in to Azure through the Azure CLI using the following command: |
| 159 | + |
| 160 | + ```azurecli |
| 161 | + az login |
| 162 | + ``` |
| 163 | + |
| 164 | + #### [PowerShell](#tab/sign-in-powershell) |
| 165 | + |
| 166 | + Sign-in to Azure using PowerShell via the following command: |
| 167 | + |
| 168 | + ```azurepowershell |
| 169 | + Connect-AzAccount |
| 170 | + ``` |
| 171 | + |
| 172 | +2. To use `DefaultAzureCredential`, make sure that the **@azure\identity** package is [installed](#install-the-packages), and the class is imported: |
| 173 | + |
| 174 | + :::code language="typescript" source="~/azure_storage-snippets/blobs/quickstarts/TypeScript/V12/nodejs/src/index.ts" id="snippet_StorageAcctInfo_without_secrets"::: |
| 175 | + |
| 176 | +3. Add this code inside the `try` block. When the code runs on your local workstation, `DefaultAzureCredential` uses the developer credentials of the prioritized tool you're logged into to authenticate to Azure. Examples of these tools include Azure CLI or Visual Studio Code. |
| 177 | + |
| 178 | + :::code language="typescript" source="~/azure_storage-snippets/blobs/quickstarts/TypeScript/V12/nodejs/src/index.ts" id="snippet_StorageAcctInfo_create_client"::: |
| 179 | + |
| 180 | +4. Make sure to update the storage account name, `AZURE_STORAGE_ACCOUNT_NAME`, in the `.env` file or your environment's variables. The storage account name can be found on the overview page of the Azure portal. |
| 181 | + |
| 182 | + :::image type="content" source="./media/storage-quickstart-blobs-python/storage-account-name.png" alt-text="A screenshot showing how to find the storage account name."::: |
| 183 | + |
| 184 | + > [!NOTE] |
| 185 | + > When deployed to Azure, this same code can be used to authorize requests to Azure Storage from an application running in Azure. However, you'll need to enable managed identity on your app in Azure. Then configure your storage account to allow that managed identity to connect. For detailed instructions on configuring this connection between Azure services, see the [Auth from Azure-hosted apps](/azure/developer/javascript/sdk/authentication/azure-hosted-apps) tutorial. |
| 186 | + |
| 187 | +### [Connection String](#tab/connection-string) |
| 188 | + |
| 189 | +A connection string includes the storage account access key and uses it to authorize requests. Always be careful to never expose the keys in an unsecure location. |
| 190 | + |
| 191 | +> [!NOTE] |
| 192 | +> To authorize data access with the storage account access key, you'll need permissions for the following Azure RBAC action: [Microsoft.Storage/storageAccounts/listkeys/action](../../role-based-access-control/resource-provider-operations.md#microsoftstorage). The least privileged built-in role with permissions for this action is [Reader and Data Access](../../role-based-access-control/built-in-roles.md#reader-and-data-access), but any role which includes this action will work. |
| 193 | + |
| 194 | +[!INCLUDE [retrieve credentials](../../../includes/retrieve-credentials.md)] |
| 195 | + |
| 196 | +#### Configure your storage connection string |
| 197 | + |
| 198 | +After you copy the connection string, write it to a new environment variable on the local machine running the application. To set the environment variable, open a console window, and follow the instructions for your operating system. Replace `<yourconnectionstring>` with your actual connection string. |
| 199 | + |
| 200 | +**Windows**: |
| 201 | + |
| 202 | +```cmd |
| 203 | +setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>" |
| 204 | +``` |
| 205 | + |
| 206 | +After you add the environment variable in Windows, you must start a new instance of the command window. |
| 207 | + |
| 208 | +**Linux**: |
| 209 | + |
| 210 | +```bash |
| 211 | +export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>" |
| 212 | +``` |
| 213 | + |
| 214 | +**.env file**: |
| 215 | + |
| 216 | +```bash |
| 217 | +AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>" |
| 218 | +``` |
| 219 | + |
| 220 | +The following code retrieves the connection string for the storage account from the environment variable created earlier, and uses the connection string to construct a service client object. |
| 221 | + |
| 222 | +Add this code inside a `try/catch` block: |
| 223 | + |
| 224 | +:::code language="typescript" source="~/azure_storage-snippets/blobs/quickstarts/TypeScript/V12/nodejs/src/index-with-connection-string.ts" id="snippet_StorageAcctInfo__with_secrets"::: |
| 225 | + |
| 226 | +> [!IMPORTANT] |
| 227 | +> The account access key should be used with caution. If your account access key is lost or accidentally placed in an insecure location, your service may become vulnerable. Anyone who has the access key is able to authorize requests against the storage account, and effectively has access to all the data. `DefaultAzureCredential` provides enhanced security features and benefits and is the recommended approach for managing authorization to Azure services. |
| 228 | +
|
| 229 | +--- |
| 230 | + |
| 231 | +## Create a container |
| 232 | + |
| 233 | +Create a new container in the storage account. The following code example takes a [BlobServiceClient](/javascript/api/@azure/storage-blob/blobserviceclient) object and calls the [getContainerClient](/javascript/api/@azure/storage-blob/blobserviceclient#getcontainerclient-string-) method to get a reference to a container. Then, the code calls the [create](/javascript/api/@azure/storage-blob/containerclient#create-containercreateoptions-) method to actually create the container in your storage account. |
| 234 | + |
| 235 | +Add this code to the end of the `try` block: |
| 236 | + |
| 237 | +:::code language="typescript" source="~/azure_storage-snippets/blobs/quickstarts/TypeScript/V12/nodejs/src/index.ts" id="snippet_CreateContainer"::: |
| 238 | + |
| 239 | +To learn more about creating a container, and to explore more code samples, see [Create a blob container with JavaScript](storage-blob-container-create-javascript.md). |
| 240 | + |
| 241 | +> [!IMPORTANT] |
| 242 | +> Container names must be lowercase. For more information about naming containers and blobs, see [Naming and Referencing Containers, Blobs, and Metadata](/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata). |
| 243 | +
|
| 244 | +## Upload blobs to a container |
| 245 | + |
| 246 | +Upload a blob to the container. The following code gets a reference to a [BlockBlobClient](/javascript/api/@azure/storage-blob/blockblobclient) object by calling the [getBlockBlobClient](/javascript/api/@azure/storage-blob/containerclient#getblockblobclient-string-) method on the [ContainerClient](/javascript/api/@azure/storage-blob/containerclient) from the [Create a container](#create-a-container) section. |
| 247 | + |
| 248 | +The code uploads the text string data to the blob by calling the [upload](/javascript/api/@azure/storage-blob/blockblobclient#upload-httprequestbody--number--blockblobuploadoptions-) method. |
| 249 | + |
| 250 | +Add this code to the end of the `try` block: |
| 251 | + |
| 252 | +:::code language="typescript" source="~/azure_storage-snippets/blobs/quickstarts/TypeScript/V12/nodejs/src/index.ts" id="snippet_UploadBlobs"::: |
| 253 | + |
| 254 | +To learn more about uploading blobs, and to explore more code samples, see [Upload a blob with JavaScript](storage-blob-upload-javascript.md). |
| 255 | + |
| 256 | +## List the blobs in a container |
| 257 | + |
| 258 | +List the blobs in the container. The following code calls the [listBlobsFlat](/javascript/api/@azure/storage-blob/containerclient#listblobsflat-containerlistblobsoptions-) method. In this case, only one blob is in the container, so the listing operation returns just that one blob. |
| 259 | + |
| 260 | +Add this code to the end of the `try` block: |
| 261 | + |
| 262 | +:::code language="typescript" source="~/azure_storage-snippets/blobs/quickstarts/TypeScript/V12/nodejs/src/index.ts" id="snippet_ListBlobs"::: |
| 263 | + |
| 264 | +To learn more about listing blobs, and to explore more code samples, see [List blobs with JavaScript](storage-blobs-list-javascript.md). |
| 265 | + |
| 266 | +## Download blobs |
| 267 | + |
| 268 | +Download the blob and display the contents. The following code calls the [download](/javascript/api/@azure/storage-blob/blockblobclient#download-undefined---number--undefined---number--blobdownloadoptions-) method to download the blob. |
| 269 | + |
| 270 | +Add this code to the end of the `try` block: |
| 271 | + |
| 272 | +:::code language="typescript" source="~/azure_storage-snippets/blobs/quickstarts/TypeScript/V12/nodejs/src/index.ts" id="snippet_DownloadBlobs"::: |
| 273 | + |
| 274 | +The following code converts a stream back into a string to display the contents. |
| 275 | + |
| 276 | +Add this code *after* the `main` function: |
| 277 | + |
| 278 | +:::code language="typescript" source="~/azure_storage-snippets/blobs/quickstarts/TypeScript/V12/nodejs/src/index.ts" id="snippet_ConvertStreamToText"::: |
| 279 | + |
| 280 | +To learn more about downloading blobs, and to explore more code samples, see [Download a blob with JavaScript](storage-blob-download-javascript.md). |
| 281 | + |
| 282 | +## Delete a container |
| 283 | + |
| 284 | +Delete the container and all blobs within the container. The following code cleans up the resources created by the app by removing the entire container using the [delete](/javascript/api/@azure/storage-blob/containerclient#delete-containerdeletemethodoptions-) method. |
| 285 | + |
| 286 | +Add this code to the end of the `try` block: |
| 287 | + |
| 288 | +:::code language="typescript" source="~/azure_storage-snippets//blobs/quickstarts/TypeScript/V12/nodejs/src/index.ts" id="snippet_DeleteContainer"::: |
| 289 | + |
| 290 | +To learn more about deleting a container, and to explore more code samples, see [Delete and restore a blob container with JavaScript](storage-blob-container-delete-javascript.md). |
| 291 | + |
| 292 | +## Run the code |
| 293 | + |
| 294 | +1. From a Visual Studio Code terminal, build the app. |
| 295 | + |
| 296 | + ```console |
| 297 | + tsc |
| 298 | + ``` |
| 299 | + |
| 300 | +1. Run the app. |
| 301 | + |
| 302 | + ```console |
| 303 | + node dist/index.js |
| 304 | + ``` |
| 305 | + |
| 306 | +1. The output of the app is similar to the following example: |
| 307 | + |
| 308 | + ```output |
| 309 | + Azure Blob storage - JavaScript quickstart sample |
| 310 | + |
| 311 | + Creating container... |
| 312 | + quickstart4a0780c0-fb72-11e9-b7b9-b387d3c488da |
| 313 | + |
| 314 | + Uploading to Azure Storage as blob: |
| 315 | + quickstart4a3128d0-fb72-11e9-b7b9-b387d3c488da.txt |
| 316 | + |
| 317 | + Listing blobs... |
| 318 | + quickstart4a3128d0-fb72-11e9-b7b9-b387d3c488da.txt |
| 319 | + |
| 320 | + Downloaded blob content... |
| 321 | + Hello, World! |
| 322 | + |
| 323 | + Deleting container... |
| 324 | + Done |
| 325 | + ``` |
| 326 | + |
| 327 | +Step through the code in your debugger and check your [Azure portal](https://portal.azure.com) throughout the process. Check to see that the container is being created. You can open the blob inside the container and view the contents. |
| 328 | + |
| 329 | +## Clean up resources |
| 330 | + |
| 331 | +1. When you're done with this quickstart, delete the `blob-quickstart` directory. |
| 332 | +1. If you're done using your Azure Storage resource, use the [Azure CLI to remove the Storage resource](storage-quickstart-blobs-cli.md#clean-up-resources). |
| 333 | + |
| 334 | +## Next steps |
| 335 | + |
| 336 | +In this quickstart, you learned how to upload, download, and list blobs using JavaScript. |
| 337 | + |
| 338 | +To see Blob storage sample apps, continue to: |
| 339 | + |
| 340 | +> [!div class="nextstepaction"] |
| 341 | +> [Azure Blob Storage library for TypeScript samples](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/storage/storage-blob/samples/v12/typescript) |
| 342 | + |
| 343 | +- To learn more, see the [Azure Blob Storage client libraries for JavaScript](/javascript/api/overview/azure/storage-blob-readme). |
| 344 | +- For tutorials, samples, quickstarts, and other documentation, visit [Azure for JavaScript and Node.js developers](/azure/developer/javascript/). |
0 commit comments