firebase函数将json作为文件保存在存储中

问题描述 投票:0回答:1

我想将一个简单的json保存到Firebase存储中。这是我正在使用的代码:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp();

exports.logTeams = functions.https.onRequest(async () => {

    const fileName = 'teams.json';
    const bucketFileStream = admin
        .storage()
        .bucket()
        .file(fileName)
        .createWriteStream({contentType: 'application/json'});

    bucketFileStream.write('{}');
    bucketFileStream.end();

    admin.storage().bucket().upload(fileName)
        .then(value => {
            console.log(value);
        })
        .catch(reason => {
            console.log(reason);
        });

    return fileName + ' saved ' + 'with bucketstream ' + bucketFileStream;
});

以某种方式存储文件,但在日志中仍然出现此错误:

{ Error: ENOENT: no such file or directory, stat 'teams.json' errno: -2, code: 'ENOENT', syscall: 'stat', path: 'teams.json' }

我很困惑,为什么它在工作时会出现错误?

node.js typescript firebase google-cloud-functions firebase-storage
1个回答
0
投票

向道格·史蒂文森致敬!

我的代码以前没有任何意义。我这样修改了它,现在可以正常工作:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp();

exports.logTeams = functions.https.onRequest(async (req, res) => {

    const bucketFileStream = admin
        .storage()
        .bucket()
        .file('teams.json')
        .createWriteStream({
            contentType: 'application/json',
        });

    bucketFileStream.write('{}');
    bucketFileStream.end();

    res.sendStatus(200);
});
© www.soinside.com 2019 - 2024. All rights reserved.