如何使用节点Js写入和检索临时二进制文件?

时间:2018-12-06 19:21:58

标签: javascript node.js google-cloud-storage firebase-storage

问题

我正在与Google Text To Speech (TTS)合作,以便将生成的二进制音频文件保存到Google Cloud Storage (GCS)

在Firebase的Cloud Functions环境中,保存本地二进制文件似乎不是一个好主意。因此,我正在寻找如何编写和检索临时二进制文件?。当我尝试检索当前创建的临时文件时,会收到错误消息。

在试图将临时文件显示为已保存在日志下方的解决方案中,然后我尝试在文件创建回调的成功部分中检索临时文件。

错误

Error: Cannot parse JSON response  
at ApiError (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/build/src/util.js:43:9)
  at Util.parseHttpRespBody (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/build/src/util.js:167:42)
  at Util.handleResp (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/build/src/util.js:116:117)
  at retryRequest (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/build/src/util.js:403:22)
  at onResponse (/user_code/node_modules/@google-cloud/storage/node_modules/retry-request/index.js:200:7)
  at /user_code/node_modules/@google-cloud/storage/node_modules/teeny-request/build/src/index.js:158:17
  at process._tickDomainCallback (internal/process/next_tick.js:135:7)

尝试的解决方案

const admin = require('firebase-admin');
const functions = require('firebase-functions');
const path = require('path');
const os = require('os');
const {Storage} = require('@google-cloud/storage');
const projectId = 'coinverse-media-staging';
const storage = new Storage({
  projectId: projectId,
});

const fs = require('fs');
const textToSpeech = require('@google-cloud/text-to-speech');

const client = new textToSpeech.TextToSpeechClient();

admin.initializeApp();

const text = 'Hello, world!';

const request = {
   input: {text: text},
   // Select the language and SSML Voice Gender (optional)
   voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
   // Select the type of audio encoding
   audioConfig: {audioEncoding: 'MP3'},
}; 

exports.getAudiocast = functions.https.onCall((data, context) => {

var bucket = storage.bucket('gs://[project-name].appspot.com/content/feeds/en-audio/');

client.synthesizeSpeech(request, (err, response) => {
    if (err) {
      console.error('ERROR:', err);
      return;
    }

    const tempFile = path.join(os.tmpdir(), (data.id + '.mp3'));

    fs.writeFile(tempFile, response.audioContent, 'binary', err => {
      if (err) {
        console.error('ERROR:', err);
        return;
      }

      console.log('Audio content written to file: ' + tempFile);

      bucket.upload(tempFile), function(err, file) {
        if (!err) {
          console.log('Audiocast uploaded!');
        } else {
          console.error('Audiocast upload error: ' + err.message);
        }
      };
    });  
});

return {
    filePath: "cloudStorage/someFilePath",
};
});

下一步

我将尝试上传普通的文本文件而不是二进制文件,以查看是否存在临时文件格式。

3 个答案:

答案 0 :(得分:2)

感谢@Doug_Stevenson和@AndersonMendes提供指导!

解决方案

我在我的 Google Cloud Storage 中同时包含了 bucket ID和文件路径,该文件路径是错误的来源。

桶形字符串

var bucket = storage.bucket('gs://[projectName].appspot.com');

GCS上传方法

bucket.upload(tempFile, { destination: ("directory/someFolderName/" + fileName) }, (err, file) => {
        if (!err) {
          console.log('Audiocast uploaded!');
        } else {
          console.error('Audiocast upload error: ' + err.message);
        }
      });

答案 1 :(得分:1)

由于该平台上缺乏信誉点,我无法发表评论。

您需要删除临时文件

https://firebase.google.com/docs/functions/tips#always_delete_temporary_files

答案 2 :(得分:0)

相同的答案,我的代码:

    const http = require('http');
    const fs = require('fs');
    const path = require('path');
    const os = require('os');

    var options = {
        destination: ('Audio/' + longLanguage + '/' + pronunciation + '/' + word + '.mp3'),
        contentType: 'audio/' + audioType
    };

    function oedPromise() {
        return new Promise(function(resolve, reject) {
          const tempFile = path.join(os.tmpdir(), (word + '.mp3'));
          const file = fs.createWriteStream(tempFile)
          http.get(apiURL, function(response) {
            response.pipe(file)
            .on('error', function(error) {
              console.error(error);
              reject(error);
            })
            .on('finish', function() {
              myBucket.upload(tempFile, options)
              .then(function(data) {
                return;
              })
              .catch(error => console.error(error));
            });
          });
        });
    }