问题
如何将 async
辅助方法添加到 Cloud Functions 的 index.js 文件中?需要一个 async
函数才能使用 await
在将 fs.writefile
转换为一个 Promise 文件时,如 fpromises.StackOverflow 中所述: 同步的东西。但是, lint 不赞成在 exports
函数之外向 index.js 文件添加其他方法。
错误
第 84 行引用辅助函数 async function writeFile
。
Users/adamhurwitz/coinverse/coinverse-cloud-functions/functions/index.js 84:7 错误解析错误:意外的令牌函数
✖ 1 个问题(1 个错误,0 个警告)
错误!代码生命周期
错误!错误号 1
错误!函数@ lint:
eslint .
错误!退出状态 1
错误!
错误! functions@lint 脚本失败。
错误!这可能不是 npm 的问题。上面可能有额外的日志输出。
错误!可以在以下位置找到此运行的完整日志:
错误! /Users/adamhurwitz/.npm/_logs/2018-12-12T01_47_50_684Z-debug.log
错误:函数预部署错误:命令以非零退出代码 1 终止
设置
索引.js
const path = require('path');
const os = require('os');
const fs = require('fs');
const fsPromises = require('fs').promises;
const util = require('util');
const admin = require('firebase-admin');
const functions = require('firebase-functions');
const {Storage} = require('@google-cloud/storage');
const textToSpeech = require('@google-cloud/text-to-speech');
const storage = new Storage({
projectId: 'project-id',
});
const client = new textToSpeech.TextToSpeechClient();
admin.initializeApp();
exports.getAudiocast = functions.https.onCall((data, context) => {
const bucket = storage.bucket('gs://[bucket-name].appspot.com');
var fileName;
var tempFile;
var filePath;
return client.synthesizeSpeech({
input: {text: data.text },
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
audioConfig: {audioEncoding: 'MP3'},
})
.then(responses => {
var response = responses[0];
fileName = data.id + '.mp3'
tempFile = path.join(os.tmpdir(), fileName);
return writeFile(tempFile, response.audioContent)
})
.catch(err => {
console.error("Synthesize Speech Error: " + err);
})
.then(() => {
filePath = "filePath/" + fileName;
return bucket.upload(tempFile, { destination: filePath })
})
.catch(err => {
console.error("Write Temporary Audio File Error: " + err);
})
.then(() => {
return { filePath: filePath }
})
.catch(err => {
console.error('Upload Audio to GCS ERROR: ' + err);
});
});
辅助方法:
async function writeFile(tempFile, audioContent) {
await fs.writeFile(tempFile, audioContent, 'binary');
}
尝试的解决方案
按照 Cloud Functions for Firebase Async Await style 中的建议启用 Node.js 8 。
设置 Node.js 版本
"engines": {"node": "8"}
return await fs.writeFile(tempFile, audioContent, 'binary');
Lint 不喜欢这种解决方案。
原文由 AdamHurwitz 发布,翻译遵循 CC BY-SA 4.0 许可协议
Node.js 8 - 承诺
按照 Cloud Functions for Firebase Async Await style 中的建议启用 Node.js 8 。
"engines": {"node": "8"}
promisify
const writeFile = util.promisify(fs.writeFile);
return writeFile(tempFile, response.audioContent, 'binary')
Pre Node.js 8 - 手动转换
这是一种将回调转换为 Promises 的较旧方法,如本答案所概述的那样,该 答案 涉及有关 Google Text To Speech ( TTS ) 的更具体问题。