Windows 10下Node.js本地运行Google异步函数及环境变量配置
在Windows 10本地模拟AWS Lambda运行Google异步语音识别的方案
我来帮你搞定这个问题,分步骤梳理清楚:
第一步:先把环境配置捋顺
- 先检查你的
.env文件:GOOGLE_APPLICATION_CREDENTIALS的路径在Windows下要注意格式,要是密钥文件在项目根目录,写成相对路径./GDeveloperKey.json就行,或者用绝对路径(比如C:\your-project-folder\GDeveloperKey.json),避免路径解析出错。 - 安装必需的依赖:打开项目根目录的命令提示符,运行
npm install @google-cloud/speech dotenv,dotenv用来加载.env里的环境变量。
第二步:本地模拟AWS Lambda的Handler运行方式
AWS Lambda的核心就是那个exports.handler异步函数,本地模拟有两种简单方案:
方式一:自己写本地启动脚本(最快捷,不用额外工具)
直接写个小脚本手动触发handler,模拟Lambda的调用逻辑:
- 把语音识别代码整合到Lambda handler里,同时加上环境变量加载,完整代码保存为
index.js:
require('dotenv').config(); const speech = require('@google-cloud/speech'); const client = new speech.SpeechClient(); exports.handler = async (event, context, callback) => { try { // 替换成你的实际配置 const gcsUri = 'gs://your-bucket-name/audio.raw'; const encoding = 'LINEAR16'; // 对应你的.raw文件编码,LINEAR16是常见PCM格式 const sampleRateHertz = 16000; // 必须和音频实际采样率一致 const languageCode = 'en-US'; // 换成目标语言,比如zh-CN const config = { encoding: encoding, sampleRateHertz: sampleRateHertz, languageCode: languageCode, }; const audio = { uri: gcsUri, }; const request = { config: config, audio: audio, }; // 启动异步识别任务 const [operation] = await client.longRunningRecognize(request); const [response] = await operation.promise(); // 整理转录结果 const transcription = response.results .map(result => result.alternatives[0].transcript) .join('\n'); console.log('转录结果:\n', transcription); // 模拟Lambda返回格式 callback(null, { statusCode: 200, body: JSON.stringify({ transcription: transcription }) }); } catch (error) { console.error('识别出错:', error); callback(error); } };
- 创建本地启动脚本
local-run.js,用来模拟Lambda的event、context和callback:
const { handler } = require('./index'); // 模拟Lambda的event(可以根据需求传入参数,比如从event里读取GCS路径) const mockEvent = {}; // 模拟Lambda的context(空对象即可) const mockContext = {}; // 模拟Lambda的回调函数 const mockCallback = (error, result) => { if (error) { console.error('Handler执行失败:', error); process.exit(1); } else { console.log('Handler执行成功,返回结果:', result); process.exit(0); } }; // 触发handler执行 handler(mockEvent, mockContext, mockCallback);
- 运行测试:在命令提示符里执行
node local-run.js,就能看到转录结果或错误信息了。
方式二:用AWS SAM CLI(更贴近真实Lambda环境)
如果想模拟更真实的Lambda运行环境,可以用AWS SAM CLI:
- 先安装AWS SAM CLI(Windows下可以用Chocolatey或者官方安装包)
- 在项目根目录创建
template.yaml配置文件:
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: SpeechRecognitionFunction: Type: AWS::Serverless::Function Properties: Runtime: nodejs18.x # 对应你的Node.js版本 Handler: index.handler Environment: Variables: HOST: localhost PORT: 3000 GOOGLE_APPLICATION_CREDENTIALS: GDeveloperKey.json
- 执行
sam local invoke SpeechRecognitionFunction,SAM会模拟Lambda环境运行你的handler。
第三步:关键注意事项
- 确保你的Google Cloud账号已启用Speech-to-Text API,且
GDeveloperKey.json是有效的服务账号密钥。 - 音频文件的编码、采样率必须和代码里的
config参数完全匹配,否则会识别失败。 - 如果遇到环境变量加载问题,直接把
GOOGLE_APPLICATION_CREDENTIALS设为绝对路径试试。
内容的提问来源于stack exchange,提问作者sigur7
相关产品推荐
相关产品推荐

