javascript - 在node.js中运行示例代码成功,但在浏览器中运行修改后的代码失败

标签 javascript node.js azure asynchronous browser

我运行了网页中给出的代码示例

https://github.com/Azure/azure-sdk-for-js/blob/feature/storage/sdk/storage/storage-blob/samples/javascript/basic.js

然而,当我按照网页中给出的说明尝试在浏览器中运行代码时,在node.js中成功了

https://github.com/Azure/azure-sdk-for-js/tree/feature/storage/sdk/storage/storage-blob#javascript-bundle

https://github.com/Azure/azure-sdk-for-js/tree/feature/storage/sdk/storage/storage-blob#download-a-blob-and-convert-it-to-a-string-browsers

我收到一个错误

Uncaught SyntaxError: Unexpected token export

我使用代码示例中的相同代码创建了一个 .js 文件,并根据说明更改了部分代码,以便在 Chrome 中运行。完成后,编辑器中已经出现 5 个错误,例如

'types' can only be used in a .ts file.
'type arguments' can only be used in a .ts file.

但是,我认为如果我在 Chrome 中运行代码,这可能不是问题。因此,我继续将此 .js 文件附加到在同一目录中创建的 .html 文件中的 scipt 标记。

这是示例中给出的 .js 代码:

/* 
 Setup: Enter your storage account name and shared key in main()
*/

const { BlobServiceClient, SharedKeyCredential } = require("../.."); // Change to "@azure/storage-blob" in your package

async function main() {
  // Enter your storage account name and shared key
  const account = "";
  const accountKey = "";

  // Use SharedKeyCredential with storage account and account key
  // SharedKeyCredential is only avaiable in Node.js runtime, not in browsers
  const sharedKeyCredential = new SharedKeyCredential(account, accountKey);

  // ONLY AVAILABLE IN NODE.JS RUNTIME
  // DefaultAzureCredential will first look for Azure Active Directory (AAD)
  // client secret credentials in the following environment variables:
  //
  // - AZURE_TENANT_ID: The ID of your AAD tenant
  // - AZURE_CLIENT_ID: The ID of your AAD app registration (client)
  // - AZURE_CLIENT_SECRET: The client secret for your AAD app registration
  //
  // If those environment variables aren't found and your application is deployed
  // to an Azure VM or App Service instance, the managed service identity endpoint
  // will be used as a fallback authentication source.
  // const defaultAzureCredential = new DefaultAzureCredential();

  // Use TokenCredential with OAuth token
  // const tokenCredential = new RawTokenCredential("token");
  // tokenCredential.token = "renewedToken"; // Renew the token by updating token field of token credential

  // Use AnonymousCredential when url already includes a SAS signature
  // const anonymousCredential = new AnonymousCredential();

  // List containers
  const blobServiceClient = new BlobServiceClient(
    // When using AnonymousCredential, following url should include a valid SAS or support public access
    `https://${account}.blob.core.windows.net`,
    sharedKeyCredential
  );

  let i = 1;
  for await (const container of blobServiceClient.listContainers()) {
    console.log(`Container ${i++}: ${container.name}`);
  }

  // Create a container
  const containerName = `newcontainer${new Date().getTime()}`;
  const containerClient = blobServiceClient.getContainerClient(containerName);

  const createContainerResponse = await containerClient.create();
  console.log(`Create container ${containerName} successfully`, createContainerResponse.requestId);

  // Create a blob
  const content = "hello";
  const blobName = "newblob" + new Date().getTime();
  const blobClient = containerClient.getBlobClient(blobName);
  const blockBlobClient = blobClient.getBlockBlobClient();
  const uploadBlobResponse = await blockBlobClient.upload(content, content.length);
  console.log(`Upload block blob ${blobName} successfully`, uploadBlobResponse.requestId);

  // List blobs
  i = 1;
  for await (const blob of containerClient.listBlobsFlat()) {
    console.log(`Blob ${i++}: ${blob.name}`);
  }

  // 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 blobClient.download(0);
  console.log(
    "Downloaded blob content",
    await streamToString(downloadBlockBlobResponse.readableStreamBody)
  );

  // Delete container
  await containerClient.delete();

  console.log("deleted container");
}

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

// An async method returns a Promise object, which is compatible with then().catch() coding style.
main()
  .then(() => {
    console.log("Successfully executed sample.");
  })
  .catch((err) => {
    console.log(err.message);
  });

这是我为了在 Chrome 中运行而创建的 .js 文件:

/* 
 Setup: Enter your storage account name and shared key in main()
*/

const { BlobServiceClient, SharedKeyCredential } = require("@azure/storage-blob"); // Change to "@azure/storage-blob" in your package

async function main() {
  // Enter your storage account name and shared key
  const account = "";
  const accountKey = "";

  // Use SharedKeyCredential with storage account and account key
  // SharedKeyCredential is only avaiable in Node.js runtime, not in browsers
  const sharedKeyCredential = new SharedKeyCredential(account, accountKey);

  // ONLY AVAILABLE IN NODE.JS RUNTIME
  // DefaultAzureCredential will first look for Azure Active Directory (AAD)
  // client secret credentials in the following environment variables:
  //
  // - AZURE_TENANT_ID: The ID of your AAD tenant
  // - AZURE_CLIENT_ID: The ID of your AAD app registration (client)
  // - AZURE_CLIENT_SECRET: The client secret for your AAD app registration
  //
  // If those environment variables aren't found and your application is deployed
  // to an Azure VM or App Service instance, the managed service identity endpoint
  // will be used as a fallback authentication source.
  // const defaultAzureCredential = new DefaultAzureCredential();

  // Use TokenCredential with OAuth token
  // const tokenCredential = new RawTokenCredential("token");
  // tokenCredential.token = "renewedToken"; // Renew the token by updating token field of token credential

  // Use AnonymousCredential when url already includes a SAS signature
  // const anonymousCredential = new AnonymousCredential();

  // List containers
  const blobServiceClient = new BlobServiceClient(
    // When using AnonymousCredential, following url should include a valid SAS or support public access
    `https://${account}.blob.core.windows.net`,
    sharedKeyCredential
  );

  let i = 1;
  for await (const container of blobServiceClient.listContainers()) {
    console.log(`Container ${i++}: ${container.name}`);
  }

  // Create a container
  const containerName = `newcontainer${new Date().getTime()}`;
  const containerClient = blobServiceClient.getContainerClient(containerName);

  const createContainerResponse = await containerClient.create();
  console.log(`Create container ${containerName} successfully`, createContainerResponse.requestId);

  // Create a blob
  const content = "hello";
  const blobName = "newblob" + new Date().getTime();
  const blobClient = containerClient.getBlobClient(blobName);
  const blockBlobClient = blobClient.getBlockBlobClient();
  const uploadBlobResponse = await blockBlobClient.upload(content, content.length);
  console.log(`Upload block blob ${blobName} successfully`, uploadBlobResponse.requestId);

  // List blobs
  i = 1;
  for await (const blob of containerClient.listBlobsFlat()) {
    console.log(`Blob ${i++}: ${blob.name}`);
  }

 // Get blob content from position 0 to the end
  // In browsers, get downloaded data by accessing downloadBlockBlobResponse.blobBody
  const downloadBlockBlobResponse = await blobClient.download(0);
  console.log(
    "Downloaded blob content",
    await blobToString(downloadBlockBlobResponse.blobBody)
  );

  // Delete container
  await containerClient.delete();

  console.log("deleted container");
}

// [Browsers only] A helper method used to convert a browser Blob into string.
export async function blobToString(blob: Blob): Promise<string> {
    const fileReader = new FileReader();
    return new Promise<string>((resolve, reject) => {
      fileReader.onloadend = (ev: any) => {
        resolve(ev.target!.result);
      };
      fileReader.onerror = reject;
      fileReader.readAsText(blob);
    });
  }

// An async method returns a Promise object, which is compatible with then().catch() coding style.
main()
  .then(() => {
    console.log("Successfully executed sample.");
  })
  .catch((err) => {
    console.log(err.message);
  });

这是我在 .html 文件中输入的代码:

<html>
    <head>
        <script src="azure-storage-blob.min.js"></script>
        <script src="browsertest.js"></script>
    </head>
</html>

我在控制台中收到此错误:

browsertest.js:84 Uncaught SyntaxError: Unexpected token export

但是我在编辑器中遇到以下错误:

'types' can only be used in a .ts file.
'type arguments' can only be used in a .ts file.

所以我想知道哪一个才是真正的问题?

我应该将网页中给出的代码放入

https://github.com/Azure/azure-sdk-for-js/tree/feature/storage/sdk/storage/storage-blob#download-a-blob-and-convert-it-to-a-string-browsers

在 .ts 文件中并将它们编译成 JavaScript 代码?

最佳答案

您的 blobToString 函数声明和 return 语句包含 TypeScript 表示法,浏览器本身不支持该表示法。在这种情况下,您需要将 js 代码编译为浏览器 (ES5) 支持的“通用”javascript。

查看相关question

关于javascript - 在node.js中运行示例代码成功,但在浏览器中运行修改后的代码失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57487733/

相关文章:

javascript - babel preset @babel/preset-react 不喜欢我返回 JS.X 元素的 javascript 函数

javascript - 比较 JavaScript 中的时间

javascript - Create-React-App 如何从目录中导入所有 SCSS 文件?

node.js - TypeScript + Express : req. 参数

Azure DocumentDB 最短计费时间

javascript - 如何在 router.get() 方法中传递 url 作为参数?

javascript - 如何在 iMacros 中运行 Javascript

Azure ADv2 - 找不到 token.botframework.com 资源

javascript - 将超集数组叠加到顺序/顺序很重要的子集数组上(在 Javascript 中)

azure - 在 azure cli 中运行多行语句