Azure Function Linux Node.js使用@azure/storage-blob报错:Cannot read property 'startsWith' of undefined
Azure Node.js函数启动报错:Cannot read property 'startsWith' of undefined
问题场景
本地测试Azure Node.js Linux函数时,使用以下代码初始化BlobServiceClient:
import { BlobServiceClient } from "@azure/storage-blob"; const connectionString = process.env[ "AZURE_STORAGE_CONNECTION_STRING" ] as string; export const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString);
执行rm -rf dist/ && npm run-script build && func start后,出现以下核心错误:
[2023-08-15T09:06:03.568Z] Worker was unable to load function sealworker: 'Cannot read property 'startsWith' of undefined' [2023-08-15T09:06:03.568Z] Stack: TypeError: Worker was unable to load function sealworker: 'Cannot read property 'startsWith' of undefined' [2023-08-15T09:06:03.568Z] at extractConnectionStringParts (/Users/john/myApp/code/seal/azure_function/node_modules/@azure/storage-blob/dist/index.js:13654:26) [2023-08-15T09:06:03.568Z] at Function.fromConnectionString (/Users/john/myApp/code/seal/azure_function/node_modules/@azure/storage-blob/dist/index.js:24328:32)
尽管用as string做了TypeScript类型断言,仍触发该错误。
错误原因
TypeScript的as string仅为类型提示,不会改变运行时变量的实际值。报错本质是运行时process.env.AZURE_STORAGE_CONNECTION_STRING为undefined,导致BlobServiceClient.fromConnectionString接收到undefined参数,内部调用startsWith方法时触发类型错误。
解决步骤
1. 检查本地环境变量配置文件
Azure Functions本地开发依赖local.settings.json加载环境变量,确保文件中包含正确的连接字符串配置:
{ "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "xxx", "FUNCTIONS_WORKER_RUNTIME": "node", "AZURE_STORAGE_CONNECTION_STRING": "你的存储账户连接字符串" } }
注意:修改该文件后需重启func start服务,新配置才会生效。
2. 增加运行时校验
在代码中提前判断变量是否存在,避免undefined传入SDK,同时输出明确错误信息:
import { BlobServiceClient } from "@azure/storage-blob"; const connectionString = process.env.AZURE_STORAGE_CONNECTION_STRING; // 运行时校验,提前抛出明确错误 if (!connectionString) { throw new Error("环境变量AZURE_STORAGE_CONNECTION_STRING未配置或加载失败"); } export const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString);
3. 验证环境变量加载情况
可临时添加日志打印,确认环境变量是否被正确读取:
console.log("AZURE_STORAGE_CONNECTION_STRING:", process.env.AZURE_STORAGE_CONNECTION_STRING);
启动函数后查看控制台输出,若打印为undefined,说明local.settings.json未被正确加载或配置有误。
内容的提问来源于stack exchange,提问作者Kid_Learning_C
相关产品推荐
相关产品推荐

