如何查找 NodeJS 上是不是存在 Azure 文件

Posted

技术标签:

【中文标题】如何查找 NodeJS 上是不是存在 Azure 文件【英文标题】:How to find if Azure File exists on NodeJS如何查找 NodeJS 上是否存在 Azure 文件 【发布时间】:2021-10-21 04:14:52 【问题描述】:

我用的是azure文件存储,用express JS写一个后端来渲染存储在azure文件存储中的内容。

我正在编写基于https://docs.microsoft.com/en-us/javascript/api/@azure/storage-file-share/shareserviceclient?view=azure-node-latest的代码

const  ShareServiceClient, StorageSharedKeyCredential  = require("@azure/storage-file-share");

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://$account.file.core.windows.net`,
  credential
);

const shareName = "<share name>";
const fileName = "<file name>";

// [Node.js only] A helper method used to read a Node.js readable stream into a Buffer
async function streamToBuffer(readableStream) 
  return new Promise((resolve, reject) => 
    const chunks = [];
    readableStream.on("data", (data) => 
      chunks.push(data instanceof Buffer ? data : Buffer.from(data));
    );
    readableStream.on("end", () => 
      resolve(Buffer.concat(chunks));
    );
    readableStream.on("error", reject);
  );


并且可以通过

查看内容
const downloadFileResponse = await fileClient.download();
const output = await streamToBuffer(downloadFileResponse.readableStreamBody)).toString()

问题是,我只想查找文件是否存在,而不是花时间下载整个文件,我该怎么做?

我看了https://docs.microsoft.com/en-us/javascript/api/@azure/storage-file-share/shareserviceclient?view=azure-node-latest 看看文件客户端类是否有我想要的,但它似乎没有对此有用的方法。

【问题讨论】:

只需使用 Bearer 令牌调用此 URL - https://myaccount.file.core.windows.net/myshare/mydirectorypath/myfile?comp=metadata。如果返回 200 OK,则说明您有文件,否则文件不存在 - docs.microsoft.com/en-us/rest/api/storageservices/… 【参考方案1】:

如果你使用@azure/storage-file-share (version 12.x) Node 包,ShareFileClient 中有一个exists 方法。您可以使用它来查找文件是否存在。比如:

const fileExists = await fileClient.exists();//returns true or false.

【讨论】:

以上是关于如何查找 NodeJS 上是不是存在 Azure 文件的主要内容,如果未能解决你的问题,请参考以下文章

如何自己检查NodeJS的代码是不是存在内存泄漏

Azure 函数和 Azure 存储 - 实体已存在 - nodeJS

如何检查MongoDB本机nodejs驱动程序中是不是存在集合?

如何检查图像是不是在 Azure Blob 存储上发布?

Azure Function Nodejs 中是不是可以休眠?

使用NodeJS,如何将文件上传到azure容器/目录(如:test-container/folder-test)