快速入门:在 Node.js 中使用 JavaScript v12 SDK 管理 blobQuickstart: Manage blobs with JavaScript v12 SDK in Node.js

本快速入门介绍如何使用 Node.js 管理 blob。In this quickstart, you learn to manage blobs by using Node.js. Blob 是可以保存大量文本或二进制数据(包括图像、文档、流媒体和存档数据)的对象。Blobs are objects that can hold large amounts of text or binary data, including images, documents, streaming media, and archive data. 你将上传、下载和列出 Blob,并创建和删除容器。You'll upload, download, and list blobs, and you'll create and delete containers.

其他资源:Additional resources:

先决条件Prerequisites

备注

本文中所述的功能现在可用于具有分层命名空间的帐户。The features described in this article are now available to accounts that have a hierarchical namespace. 若要查看限制,请参阅 Azure Data Lake Storage Gen2 中可用的 Blob 存储功能一文。To review limitations, see the Blob storage features available in Azure Data Lake Storage Gen2 article.

设置Setting up

本部分逐步指导如何准备一个项目,使其与适用于 JavaScript 的 Azure Blob 存储客户端库 v12 配合使用。This section walks you through preparing a project to work with the Azure Blob storage client library v12 for JavaScript.

创建项目Create the project

创建名为 blob-quickstart-v12 的 JavaScript 应用程序。Create a JavaScript application named blob-quickstart-v12.

  1. 在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为项目创建新目录。In a console window (such as cmd, PowerShell, or Bash), create a new directory for the project.

    mkdir blob-quickstart-v12
    
  2. 切换到新创建的 blob-quickstart-v12 目录。Switch to the newly created blob-quickstart-v12 directory.

    cd blob-quickstart-v12
    
  3. 创建名为 package.json 的新文本文件。Create a new text file called package.json. 此文件定义 Node.js 项目。This file defines the Node.js project. 将此文件保存到 blob-quickstart-v12 目录中。Save this file in the blob-quickstart-v12 directory. 下面是文件的内容:Here is the contents of the file:

    {
        "name": "blob-quickstart-v12",
        "version": "1.0.0",
        "description": "Use the @azure/storage-blob SDK version 12 to interact with Azure Blob storage",
        "main": "blob-quickstart-v12.js",
        "scripts": {
            "start": "node blob-quickstart-v12.js"
        },
        "author": "Your Name",
        "license": "MIT",
        "dependencies": {
            "@azure/storage-blob": "^12.0.0",
            "@types/dotenv": "^4.0.3",
            "dotenv": "^6.0.0"
        }
    }
    

    如果需要,可以在 author 字段中输入自己的名字。You can put your own name in for the author field, if you'd like.

安装包Install the package

当仍在 blob-quickstart-v12 目录中时,使用 npm install 命令安装适用于 JavaScript 包的 Azure Blob 存储客户端库。While still in the blob-quickstart-v12 directory, install the Azure Blob storage client library for JavaScript package by using the npm install command. 此命令读取 package.json 文件,并安装适用于 JavaScript 包的 Azure Blob 存储客户端库 v12 及其依赖的所有库。This command reads the package.json file and installs the Azure Blob storage client library v12 for JavaScript package and all the libraries on which it depends.

npm install

设置应用框架Set up the app framework

从项目目录中执行以下操作:From the project directory:

  1. 在代码编辑器中打开另一个新文本文件Open another new text file in your code editor

  2. 添加 require 调用以加载 Azure 和 Node.js 模块Add require calls to load Azure and Node.js modules

  3. 为程序创建结构,包括基本的异常处理Create the structure for the program, including basic exception handling

    代码如下:Here's the code:

    const { BlobServiceClient } = require('@azure/storage-blob');
    const { v1: uuid} = require('uuid');
    
    async function main() {
        console.log('Azure Blob storage v12 - JavaScript quickstart sample');
        // Quick start code goes here
    }
    
    main().then(() => console.log('Done')).catch((ex) => console.log(ex.message));
    
  4. 将新文件在 blob-quickstart-v12 目录中另存为 blob-quickstart-v12.js 。Save the new file as blob-quickstart-v12.js in the blob-quickstart-v12 directory.

从 Azure 门户复制凭据Copy your credentials from the Azure portal

当示例应用程序向 Azure 存储发出请求时,必须对其进行授权。When the sample application makes a request to Azure Storage, it must be authorized. 若要对请求进行授权,请将存储帐户凭据以连接字符串形式添加到应用程序中。To authorize a request, add your storage account credentials to the application as a connection string. 按照以下步骤查看存储帐户凭据:View your storage account credentials by following these steps:

  1. 登录 Azure 门户Sign in to the Azure portal.

  2. 找到自己的存储帐户。Locate your storage account.

  3. 在存储帐户概述的“设置”部分,选择“访问密钥”。 In the Settings section of the storage account overview, select Access keys. 在这里,可以查看你的帐户访问密钥以及每个密钥的完整连接字符串。Here, you can view your account access keys and the complete connection string for each key.

  4. 找到“密钥 1”下面的“连接字符串”值,选择“复制”按钮复制该连接字符串。 Find the Connection string value under key1, and select the Copy button to copy the connection string. 下一步需将此连接字符串值添加到某个环境变量。You will add the connection string value to an environment variable in the next step.

    显示如何从 Azure 门户复制连接字符串的屏幕截图

配置存储连接字符串Configure your storage connection string

复制连接字符串以后,请将其写入运行应用程序的本地计算机的新环境变量中。After you have copied your 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. <yourconnectionstring> 替换为实际的连接字符串。Replace <yourconnectionstring> with your actual connection string.

WindowsWindows

setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"

在 Windows 中添加环境变量后,必须启动命令窗口的新实例。After you add the environment variable in Windows, you must start a new instance of the command window.

LinuxLinux

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

macOSmacOS

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

重新启动程序Restart programs

添加环境变量后,重启需要读取环境变量的任何正在运行的程序。After you add the environment variable, restart any running programs that will need to read the environment variable. 例如,重启开发环境或编辑器,然后再继续。For example, restart your development environment or editor before continuing.

对象模型Object model

Azure Blob 存储最适合存储巨量的非结构化数据。Azure Blob storage is optimized for storing massive amounts of unstructured data. 非结构化数据是不遵循特定数据模型或定义的数据(如文本或二进制数据)。Unstructured data is data that does not adhere to a particular data model or definition, such as text or binary data. Blob 存储提供了三种类型的资源:Blob storage offers three types of resources:

  • 存储帐户The storage account
  • 存储帐户中的容器A container in the storage account
  • 容器中的 blobA blob in the container

以下图示显示了这些资源之间的关系。The following diagram shows the relationship between these resources.

Blob 存储体系结构的图示

使用以下 JavaScript 类与这些资源进行交互:Use the following JavaScript classes to interact with these resources:

  • BlobServiceClientBlobServiceClient 类可用于操纵 Azure 存储资源和 blob 容器。BlobServiceClient: The BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers.
  • ContainerClientContainerClient 类可用于操纵 Azure 存储容器及其 blob。ContainerClient: The ContainerClient class allows you to manipulate Azure Storage containers and their blobs.
  • BlobClientBlobClient 类可用于操纵 Azure 存储 blob。BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs.

代码示例Code examples

这些示例代码片段演示如何使用适用于 JavaScript 的 Azure Blob 存储客户端库执行以下步骤:These example code snippets show you how to perform the following with the Azure Blob storage client library for JavaScript:

获取连接字符串Get the connection string

下面的代码从配置存储连接字符串部分中创建的环境变量中检索存储帐户的连接字符串。The code below retrieves the connection string for the storage account from the environment variable created in the Configure your storage connection string section.

main 函数内添加此代码:Add this code inside the main function:

// Retrieve the connection string for use with the application. The storage
// connection string is stored in an environment variable on the machine
// running the application called AZURE_STORAGE_CONNECTION_STRING. If the
// environment variable is created after the application is launched in a
// console or with Visual Studio, the shell or application needs to be closed
// and reloaded to take the environment variable into account.
const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING;

创建容器Create a container

确定新容器的名称。Decide on a name for the new container. 以下代码将 UUID 值追加到容器名称,确保其是唯一的。The code below appends a UUID value to the container name to ensure that it is unique.

重要

容器名称必须为小写。Container names must be lowercase. 有关命名容器和 Blob 的详细信息,请参阅命名和引用容器、Blob 和元数据For more information about naming containers and blobs, see Naming and Referencing Containers, Blobs, and Metadata.

调用 fromConnectionString 方法,创建 BlobServiceClient 类的实例。Create an instance of the BlobServiceClient class by calling the fromConnectionString method. 然后,调用 getContainerClient 方法以获取对容器的引用。Then, call the getContainerClient method to get a reference to a container. 最后,调用 create 方法在存储帐户中实际创建容器。Finally, call create to actually create the container in your storage account.

将此代码添加到 main 函数的末尾:Add this code to the end of the main function:

// Create the BlobServiceClient object which will be used to create a container client
const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);

// Create a unique name for the container
const containerName = 'quickstart' + uuidv1();

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

// Get a reference to a container
const containerClient = blobServiceClient.getContainerClient(containerName);

// Create the container
const createContainerResponse = await containerClient.create();
console.log("Container was created successfully. requestId: ", createContainerResponse.requestId);

将 blob 上传到容器中Upload blobs to a container

以下代码片段:The following code snippet:

  1. 创建要上传到 blob 的文本字符串。Creates a text string to upload to a blob.
  2. 通过从 Create a container 部分调用 ContainerClient 上的 getBlockBlobClient 方法,获取对 BlockBlobClient 对象的引用。Gets a reference to a BlockBlobClient object by calling the getBlockBlobClient method on the ContainerClient from the Create a container section.
  3. 通过调用 upload 方法,将文本字符串数据上传到 blob。Uploads the text string data to the blob by calling the upload method.

将此代码添加到 main 函数的末尾:Add this code to the end of the main function:

// Create a unique name for the blob
const blobName = 'quickstart' + uuidv1() + '.txt';

// Get a block blob client
const blockBlobClient = containerClient.getBlockBlobClient(blobName);

console.log('\nUploading to Azure storage as blob:\n\t', blobName);

// Upload data to the blob
const data = 'Hello, World!';
const uploadBlobResponse = await blockBlobClient.upload(data, data.length);
console.log("Blob was uploaded successfully. requestId: ", uploadBlobResponse.requestId);

列出容器中的 BlobList the blobs in a container

通过调用 listBlobsFlat 方法,列出容器中的 blob。List the blobs in the container by calling the listBlobsFlat method. 在这种情况下,只向容器添加了一个 blob,因此列表操作只返回那个 blob。In this case, only one blob has been added to the container, so the listing operation returns just that one blob.

将此代码添加到 main 函数的末尾:Add this code to the end of the main function:

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

// List the blob(s) in the container.
for await (const blob of containerClient.listBlobsFlat()) {
    console.log('\t', blob.name);
}

下载 BlobDownload blobs

通过调用 download 方法,下载以前创建的 blob。Download the previously created blob by calling the download method. 示例代码包括名为 streamToString 的帮助程序函数,用于将 Node.js 可读流读入字符串。The example code includes a helper function called streamToString, which is used to read a Node.js readable stream into a string.

将此代码添加到 main 函数的末尾:Add this code to the end of the main function:

// Get blob content from position 0 to the end
// In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody
// In browsers, get downloaded data by accessing downloadBlockBlobResponse.blobBody
const downloadBlockBlobResponse = await blockBlobClient.download(0);
console.log('\nDownloaded blob content...');
console.log('\t', await streamToString(downloadBlockBlobResponse.readableStreamBody));

main 函数后添加此帮助器函数:Add this helper function after the main function:

// A helper function used to read a Node.js readable stream into a string
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);
  });
}

删除容器Delete a container

以下代码使用 delete 方法删除整个容器,从而清除该应用所创建的资源。The following code cleans up the resources the app created by removing the entire container using the delete method. 也可根据需要删除本地文件。You can also delete the local files, if you like.

将此代码添加到 main 函数的末尾:Add this code to the end of the main function:

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

// Delete container
const deleteContainerResponse = await containerClient.delete();
console.log("Container was deleted successfully. requestId: ", deleteContainerResponse.requestId);

运行代码Run the code

此应用创建文本字符串,并将其上传到 Blob 存储。This app creates a text string and uploads it to Blob storage. 示例随后列出容器中的 Blob,下载 Blob 并显示下载的数据。The example then lists the blob(s) in the container, downloads the blob, and displays the downloaded data.

在控制台提示符下,导航到包含blob-quickstart-v12.py 文件的目录,然后执行以下 node 命令来运行应用。From a console prompt, navigate to the directory containing the blob-quickstart-v12.py file, then execute the following node command to run the app.

node blob-quickstart-v12.js

应用的输出类似于以下示例:The output of the app is similar to the following example:

Azure Blob storage v12 - 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

在调试器中逐步执行代码,并在执行过程中反复检查 Azure 门户Step through the code in your debugger and check your Azure portal throughout the process. 检查是否正在创建容器。Check to see that the container is being created. 可以在容器中打开 blob 并查看内容。You can open the blob inside the container and view the contents.

后续步骤Next steps

本快速入门介绍了如何使用 JavaScript 上传、下载和列出 blob。In this quickstart, you learned how to upload, download, and list blobs using JavaScript.

有关教程、示例、快速入门和其他文档,请访问:For tutorials, samples, quickstarts, and other documentation, visit: