A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-nodejs-typescript below:

Quickstart: Azure Blob storage library - TypeScript

Get started with the Azure Blob Storage client library for Node.js with TypeScript to manage blobs and containers.

In this article, you follow steps to install the package and try out example code for basic tasks.

API reference | Library source code | Package (npm) | Samples

Prerequisites Setting up

This section walks you through preparing a project to work with the Azure Blob Storage client library for Node.js.

Create the Node.js project

Create a TypeScript application named blob-quickstart.

  1. In a console window (such as cmd, PowerShell, or Bash), create a new directory for the project:

    mkdir blob-quickstart
    
  2. Switch to the newly created blob-quickstart directory:

    cd blob-quickstart
    
  3. Create a package.json file:

    npm init -y
    
  4. Open the project in Visual Studio Code:

    code .
    
  5. Edit the package.json file to add the following properties to support ESM with TypeScript:

    "type": "module",
    
Install the packages

From the project directory, install the following packages using the npm install command.

  1. Install the Azure Storage npm package:

    npm install @azure/storage-blob
    
  2. Install other dependencies used in this quickstart:

    npm install uuid dotenv @types/node @types/uuid
    
  3. Create a tsconfig.json file in the project directory with the following contents.

    {
        "compilerOptions": {
          "target": "es2022",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
          "module": "ESNext",                                /* Specify what module code is generated. */
          "moduleResolution": "node",                     /* Specify how TypeScript looks up a file from a given module specifier. */
          "outDir": "dist",                                   /* Specify an output folder for all emitted files. */
          "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
          "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
          "strict": true,                                      /* Enable all strict type-checking options. */
          "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
        }
      }
    
Object model

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:

The following diagram shows the relationship between these resources.

Use the following JavaScript classes to interact with these resources:

Code examples

These example code snippets show you how to do the following tasks with the Azure Blob Storage client library for JavaScript:

Sample code is also available on GitHub.

Application requests to Azure Blob Storage must be authorized. Using the DefaultAzureCredential class provided by the Azure Identity client library is the recommended approach for implementing passwordless connections to Azure services in your code, including Blob Storage.

You can also authorize requests to Azure Blob Storage by using the account access key. However, this approach should be used with caution. Developers must be diligent to never expose the access key in an unsecure location. Anyone who has the access key is able to authorize requests against the storage account, and effectively has access to all the data. DefaultAzureCredential offers improved management and security benefits over the account key to allow passwordless authentication. Both options are demonstrated in the following example.

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.

The order and locations in which DefaultAzureCredential looks for credentials can be found in the Azure Identity library overview.

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 once it's deployed to Azure. No code changes are required for this transition.

Assign roles to your Microsoft Entra user account

When developing locally, make sure that the user account that is accessing blob data has the correct permissions. You'll need Storage Blob Data Contributor to read and write blob data. To assign yourself this role, you'll need to be assigned the User Access Administrator role, or another role that includes the Microsoft.Authorization/roleAssignments/write action. You can assign Azure RBAC roles to a user using the Azure portal, Azure CLI, or Azure PowerShell. For more information about the Storage Blob Data Contributor role, see Storage Blob Data Contributor. For more information about the available scopes for role assignments, see Understand scope for Azure RBAC.

In this scenario, you'll assign permissions to your user account, scoped to the storage account, to follow the Principle of Least Privilege. This practice gives users only the minimum permissions needed and creates more secure production environments.

The following example will assign the Storage Blob Data Contributor role to your user account, which provides both read and write access to blob data in your storage account.

Important

In most cases it will take a minute or two for the role assignment to propagate in Azure, but in rare cases it may take up to eight minutes. If you receive authentication errors when you first run your code, wait a few moments and try again.

  1. In the Azure portal, locate your storage account using the main search bar or left navigation.

  2. On the storage account overview page, select Access control (IAM) from the left-hand menu.

  3. On the Access control (IAM) page, select the Role assignments tab.

  4. Select + Add from the top menu and then Add role assignment from the resulting drop-down menu.

  5. Use the search box to filter the results to the desired role. For this example, search for Storage Blob Data Contributor and select the matching result and then choose Next.

  6. Under Assign access to, select User, group, or service principal, and then choose + Select members.

  7. In the dialog, search for your Microsoft Entra username (usually your user@domain email address) and then choose Select at the bottom of the dialog.

  8. Select Review + assign to go to the final page, and then Review + assign again to complete the process.

To assign a role at the resource level using the Azure CLI, you first must retrieve the resource id using the az storage account show command. You can filter the output properties using the --query parameter.

az storage account show --resource-group '<your-resource-group-name>' --name '<your-storage-account-name>' --query id

Copy the output Id from the preceding command. You can then assign roles using the az role command of the Azure CLI.

az role assignment create --assignee "<user@domain>" \
    --role "Storage Blob Data Contributor" \
    --scope "<your-resource-id>"

To assign a role at the resource level using Azure PowerShell, you first must retrieve the resource ID using the Get-AzResource command.

Get-AzResource -ResourceGroupName "<yourResourceGroupname>" -Name "<yourStorageAccountName>"

Copy the Id value from the preceding command output. You can then assign roles using the New-AzRoleAssignment command in PowerShell.

New-AzRoleAssignment -SignInName <user@domain> `
    -RoleDefinitionName "Storage Blob Data Contributor" `
    -Scope <yourStorageAccountId>
Sign in and connect your app code to Azure using DefaultAzureCredential

You can authorize access to data in your storage account using the following steps:

  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.

    Sign-in to Azure through the Azure CLI using the following command:

    az login
    

    Install the Azure CLI to work with DefaultAzureCredential through Visual Studio Code.

    On the main menu of Visual Studio Code, navigate to Terminal > New Terminal.

    Sign-in to Azure through the Azure CLI using the following command:

    az login
    

    Sign-in to Azure using PowerShell via the following command:

    Connect-AzAccount
    
  2. To use DefaultAzureCredential, make sure that the @azure\identity package is installed, and the class is imported:

    import { DefaultAzureCredential } from '@azure/identity';
    
  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.

    const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME as string;
    if (!accountName) throw Error('Azure Storage accountName not found');
    
    // Add `Storage Blob Data Contributor` role assignment to the identity
    const blobServiceClient = new BlobServiceClient(
      `https://${accountName}.blob.core.windows.net`,
      new DefaultAzureCredential()
    );
    
  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.

    Note

    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 tutorial.

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.

  1. Sign in to the Azure portal.

  2. Locate your storage account.

  3. In the storage account menu pane, under Security + networking, select Access keys. Here, you can view the account access keys and the complete connection string for each key.

  4. In the Access keys pane, select Show keys.

  5. In the key1 section, locate the Connection string value. Select the Copy to clipboard icon to copy the connection string. You'll add the connection string value to an environment variable in the next section.

You can see the connection string for your storage account using the az storage account show-connection-string command.

az storage account show-connection-string --name "<your-storage-account-name>"

You can assemble a connection string with PowerShell using the Get-AzStorageAccount and Get-AzStorageAccountKey commands.

$saName = "yourStorageAccountName"
$rgName = "yourResourceGroupName"
$sa = Get-AzStorageAccount -StorageAccountName $saName -ResourceGroupName $rgName

$saKey = (Get-AzStorageAccountKey -ResourceGroupName $rgName -Name $saName)[0].Value

'DefaultEndpointsProtocol=https;AccountName=' + $saName + ';AccountKey=' + $saKey + ';EndpointSuffix=core.windows.net'
Configure your storage connection string

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.

Windows:

setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"

After you add the environment variable in Windows, you must start a new instance of the command window.

Linux:

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

.env file:

AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

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.

Add this code inside a try/catch block:

const connectionString = process.env.AZURE_STORAGE_CONNECTION_STRING as string; 
if (!connectionString) throw Error('Azure Storage connectionString not found');

Important

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.

Create a container

Create a new container in the storage account. The following code example takes a BlobServiceClient object and calls the getContainerClient method to get a reference to a container. Then, the code calls the create method to actually create the container in your storage account.

Add this code to the end of the try block:

  const containerName = 'quickstart' + uuidv4();

  console.log('\nCreating container...');
  console.log('\t', containerName);

  const containerClient = blobServiceClient.getContainerClient(containerName);
  const createContainerResponse: ContainerCreateResponse = await containerClient.create();
  console.log(
    `Container was created successfully.\n\trequestId:${createContainerResponse.requestId}\n\tURL: ${containerClient.url}`
  );

To learn more about creating a container, and to explore more code samples, see Create a blob container with JavaScript.

Upload blobs to a container

Upload a blob to the container. The following code gets a reference to a BlockBlobClient object by calling the getBlockBlobClient method on the ContainerClient from the Create a container section.

The code uploads the text string data to the blob by calling the upload method.

Add this code to the end of the try block:

  const blobName = 'quickstart' + uuidv4(); + '.txt';
  const blockBlobClient: BlockBlobClient = containerClient.getBlockBlobClient(blobName);

  console.log(
    `\nUploading to Azure storage as blob\n\tname: ${blobName}:\n\tURL: ${blockBlobClient.url}`
  );

  const data = 'Hello, World!';
  const uploadBlobResponse: BlockBlobUploadResponse = await blockBlobClient.upload(data, data.length);
  console.log(
    `Blob was uploaded successfully. requestId: ${uploadBlobResponse.requestId}`
  );

To learn more about uploading blobs, and to explore more code samples, see Upload a blob with JavaScript.

List the blobs in a container

List the blobs in the container. The following code calls the listBlobsFlat method. In this case, only one blob is in the container, so the listing operation returns just that one blob.

Add this code to the end of the try block:

  console.log('\nListing blobs...');

  for await (const blob of containerClient.listBlobsFlat()) {
    const tempBlockBlobClient: BlockBlobClient = containerClient.getBlockBlobClient(blob.name);

    console.log(
      `\n\tname: ${blob.name}\n\tURL: ${tempBlockBlobClient.url}\n`
    );
  }

To learn more about listing blobs, and to explore more code samples, see List blobs with JavaScript.

Download blobs

Download the blob and display the contents. The following code calls the download method to download the blob.

Add this code to the end of the try block:

  const offset = 0;         // start at beginning
  const length = undefined; // read all

  const downloadBlockBlobResponse: BlobDownloadResponseParsed = await blockBlobClient.download(offset, length);
  console.log('\nDownloaded blob content...');
  console.log(
    '\t',
    await streamToText(downloadBlockBlobResponse.readableStreamBody as NodeJS.ReadableStream)
  );

The following code converts a stream back into a string to display the contents.

Add this code after the main function:

// Convert stream to text
async function streamToText(readable: NodeJS.ReadableStream): Promise<string> {
  readable.setEncoding('utf8');
  let data = '';
  for await (const chunk of readable) {
    data += chunk;
  }
  return data;
}

To learn more about downloading blobs, and to explore more code samples, see Download a blob with JavaScript.

Delete a container

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 method.

Add this code to the end of the try block:

  console.log('\nDeleting container...');

  const deleteContainerResponse: ContainerDeleteResponse = await containerClient.delete();
  console.log(
    'Container was deleted successfully. requestId: ',
    deleteContainerResponse.requestId
  );

To learn more about deleting a container, and to explore more code samples, see Delete and restore a blob container with JavaScript.

Run the code
  1. From a Visual Studio Code terminal, build the app.

    tsc
    
  2. Run the app.

    node dist/index.js
    
  3. The output of the app is similar to the following example:

    Azure Blob storage - JavaScript quickstart sample
    
    Creating container...
        quickstart4a0780c0-fb72-11e9-b7b9-b387d3c488da
    
    Uploading to Azure Storage as blob:
        quickstart4a3128d0-fb72-11e9-b7b9-b387d3c488da.txt
    
    Listing blobs...
        quickstart4a3128d0-fb72-11e9-b7b9-b387d3c488da.txt
    
    Downloaded blob content...
        Hello, World!
    
    Deleting container...
    Done
    

Step through the code in your debugger and check your Azure portal throughout the process. Check to see that the container is being created. You can open the blob inside the container and view the contents.

Clean up resources
  1. When you're done with this quickstart, delete the blob-quickstart directory.
  2. If you're done using your Azure Storage resource, use the Azure CLI to remove the Storage resource.
Next step

Azure Storage samples and developer guides for JavaScript and TypeScript


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4