成功在node.js中运行示例代码,但未能在浏览器中运行修改后的代码

弗雷德

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

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-浏览器

我有一个错误

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-浏览器

在.ts文件中并将其编译为javascript代码?

安东

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

见相关问题

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在浏览器而不是命令行中运行Node.js代码

node.js-推送新代码后,浏览器中显示的页面不会更改

在使用 Intern 运行浏览器测试之前,如何在 Node 中运行一些代码?

无法运行Teaspoon CLI,但在浏览器中成功

您如何知道哪些Node.js代码将在浏览器上运行?

在Node.js中顺序运行代码

浏览器在Keycloak中成功登录后,出现“ 500错误:无法在纯承载方式下交换授权代码”

在Node.JS浏览器代码中找不到缓冲区

图像显示在浏览器中,但无法通过代码下载 (node.js)

我将如何在浏览器中测试我的 node.js 代码?

如何检测脚本是否正在浏览器或Node.js中运行?

如何让node.js和Mocha在浏览器中运行(测试)?

如何让网站在浏览器中自动运行“node index.js”?

如何让网站在浏览器中自动运行“node index.js”?

Node.js https失败,而浏览器curl和wget成功吗?

如何在VSCode中启用Node.js代码自动完成功能?

Node.js中的成语成功回调

如何从Node.js中的Ajax发布返回成功

在服务器中运行 node-rdkafka 代码

使用gem成功安装后如何在Mac上运行Node.js?

运行示例代码时出错-导出类中的类-使用React Node.js的Auth0

在Excel用户定义函数中运行node.js代码

如何在Swift中从npm运行Node JS代码

Node.js 代码未在 javascript 函数中运行

如何在 node.js 中逐行运行代码

如何使此代码在Node.Js中同步运行?

jQuery ajax成功功能在Node.js应用程序中不起作用

无法在 Chrome 开发工具中运行修改后的 js 代码

angular-node.js,HttpClient放置连接成功,但是没有成功