【发布时间】:2019-05-13 02:02:34
【问题描述】:
问题
如何将async 辅助方法添加到Cloud Functions' index.js 文件中?在将 fs.writefile 转换为 Promise 时,需要 async 函数才能使用 await,如 StackOverflow 帖子中所述:fs.writeFile in a promise, asynchronous-synchronous stuff。但是,lint 不赞成在 index.js 文件中添加 exports 函数之外的其他方法。
错误
84行引用了辅助函数async function writeFile。
用户/adamhurwitz/coinverse/coinverse-cloud-functions/functions/index.js 84:7 错误解析错误:意外的令牌函数
✖ 1 个问题(1 个错误,0 个警告)
npm 错误!代码生命周期
npm 错误!错误号 1
npm 错误!函数@ lint:
eslint .npm 错误!退出状态 1
npm 错误!
npm 错误! functions@lint 脚本失败。
npm 错误!这可能不是 npm 的问题。上面可能还有额外的日志输出。
npm 错误!可以在以下位置找到此运行的完整日志:
npm 错误! /Users/adamhurwitz/.npm/_logs/2018-12-12T01_47_50_684Z-debug.log
错误:函数预部署错误:命令以非零退出代码终止
设置
index.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。
Set Node.js version
"engines": {"node": "8"}return await fs.writeFile(tempFile, audioContent, 'binary');
Lint 不喜欢这种解决方案。
【问题讨论】:
标签: javascript node.js firebase google-cloud-functions firebase-cli