为什么我的云功能以以下状态结束:“崩溃”

时间:2020-09-22 01:15:21

标签: node.js firebase google-cloud-functions

我的功能是一个简单的Spotify下载器。它使用spotify api在youtube上搜索歌曲名称,将其下载,然后将其保存到云存储中,并更新一些Firestore字段。它在本地工作,但是当我部署到Firebase云功能时崩溃了。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const request = require('request');
const fs = require('fs')
const path = require('path');
const os = require('os');
const tmpdir = os.tmpdir();
const { promisify } = require('util')
const unlinkAsync = promisify(fs.unlink)
const fetch = require('node-fetch');
const simpleYT = require('simpleyt')
const ytdl = require('ytdl-core');

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

    // Check the storage for the song

    var db = admin.firestore()
    doc = await db.collection('music').doc(data.trackID).get()

    if (doc.exists && doc.data().downloaded) {
        return `Already downloaded.`
    }

    res = await fetch('https://accounts.spotify.com/api/token', {
        method: 'post',
        body: 'grant_type=client_credentials',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            "Authorization": 'Basic (key)'
        },

    })

    body = await res.json()
    token = body.access_token
    console.log(token);

    res = await fetch('https://api.spotify.com/v1/tracks/' + data.trackID, {
        method: 'get',
        headers: { 
            'Authorization': 'Bearer ' + token
        },
    })

    body = await res.json()
    name = body.name
    artist = body.artists[0].name

    search = await simpleYT(`${artist} ${name}`, {
        filter: 'video',
    }) 

    videoURL = search[0].uri
    localPath = tmpdir + '/m.mp3'

    bop = await new Promise((resolve, reject) => {
        ytdl(videoURL, {
            quality: 'highestaudio'
        }).pipe(fs.createWriteStream(localPath)).on("finish", function() {
            resolve('Finished')
        });
    })

    var bucket = admin.storage().bucket();
    await bucket.upload(localPath, { destination: `music/${data.trackID}.mp3` })
    
    await unlinkAsync(localPath) 

    var db = admin.firestore()
    await db.collection('music').doc(data.trackID).set({
        downloaded: true
    })

    return `Downloaded`
})

谢谢-非常感谢您的帮助!

编辑:找到修复程序。看来,使用ytdl时,它不能与云功能一起正常使用。我切换到另一个youtube mp3节点库,效果很好。

0 个答案:

没有答案