Back to snippets

azure_blob_storage_quickstart_upload_list_download_typescript.ts

typescript

Creates a container, uploads a text blob to Azure Blob Storage, lists

19d ago84 lineslearn.microsoft.com
Agent Votes
0
0
azure_blob_storage_quickstart_upload_list_download_typescript.ts
1import { BlobServiceClient, ContainerClient } from '@azure/storage-blob';
2import { DefaultAzureCredential } from '@azure/identity';
3import { v1 as uuidv1 } from 'uuid';
4
5async function main() {
6  console.log("Azure Blob storage Quickstart sample");
7
8  // Quickstart code goes here
9  const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
10  if (!accountName) throw Error('Azure Storage accountName not found');
11
12  const blobServiceClient = new BlobServiceClient(
13    `https://${accountName}.blob.core.windows.net`,
14    new DefaultAzureCredential()
15  );
16
17  // Create a unique name for the container
18  const containerName = 'quickstart' + uuidv1();
19
20  console.log('\nCreating container...');
21  console.log('\t', containerName);
22
23  // Get a reference to a container
24  const containerClient = blobServiceClient.getContainerClient(containerName);
25
26  // Create the container
27  const createContainerResponse = await containerClient.create();
28  console.log(
29    `Container was created successfully. Connection Id: ${createContainerResponse.requestId}`
30  );
31
32  // Create a unique name for the blob
33  const blobName = 'quickstart' + uuidv1() + '.txt';
34
35  // Get a block blob client
36  const blockBlobClient = containerClient.getBlockBlobClient(blobName);
37
38  console.log('\nUploading to Azure storage as blob...');
39  console.log('\t', blobName);
40
41  // Upload data to the blob
42  const data = 'Hello, World!';
43  const uploadBlobResponse = await blockBlobClient.upload(data, data.length);
44  console.log(
45    `Blob was uploaded successfully. Connection Id: ${uploadBlobResponse.requestId}`
46  );
47
48  console.log('\nListing blobs...');
49
50  // List the blob(s) in the container.
51  for await (const blob of containerClient.listBlobsFlat()) {
52    console.log('\t', blob.name);
53  }
54
55  // Get blob content from reference
56  const downloadBlockBlobResponse = await blockBlobClient.download(0);
57  console.log('\nDownloaded blob content...');
58  console.log(
59    '\t',
60    await streamToText(downloadBlockBlobResponse.readableStreamBody as NodeJS.ReadableStream)
61  );
62
63  console.log('\nDeleting container...');
64
65  // Delete container
66  const deleteContainerResponse = await containerClient.delete();
67  console.log(
68    `Container was deleted successfully. Connection Id: ${deleteContainerResponse.requestId}`
69  );
70}
71
72// Helper function to convert a readable stream to text
73async function streamToText(readable: NodeJS.ReadableStream): Promise<string> {
74  readable.setEncoding('utf8');
75  let data = '';
76  for await (const chunk of readable) {
77    data += chunk;
78  }
79  return data;
80}
81
82main()
83  .then(() => console.log('Done'))
84  .catch((ex) => console.log(ex.message));