首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Node Js写入和检索临时二进制文件?

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

Stack Overflow用户
提问于 2018-12-07 03:21:58
回答 3查看 1.6K关注 0票数 2

问题

为了将生成的二进制音频文件保存到Google Cloud Storage (),我正在使用Google Text To Speech ()

在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",
};
});

下一步

我会尝试上传一个普通的文本文件,而不是二进制文件,看看是不是临时文件格式有问题。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-12-07 07:56:46

感谢@Doug_Stevenson和@AndersonMendes的指导!

解决方案

我将存储桶的 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);
        }
      });
票数 2
EN

Stack Overflow用户

发布于 2019-09-21 11:20:32

由于在这个平台上缺乏名誉点,我不能发表评论。

你需要删除你的临时文件

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

票数 1
EN

Stack Overflow用户

发布于 2019-05-07 00:21:53

同样的答案,我的代码是:

    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));
            });
          });
        });
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53658279

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档