Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

node.js - Download Firebase Storage File on Express Request

I am trying to code an Express API Endpoint allowing me to directly download a file located in Firebase Storage when hitting it. It should look like this:

const app = require('express')();

app.get("/download", (req, res) => {
    // Download File on Client Side
});

app.listen(8080);

I have tried using Google-Cloud Storage (After some googling), but I constantly get that it cannot find the file, so I suppose there is a difference between Google-Cloud Storage and Firebase Storage, that I am missing some initialization. What I have at the moment is:

const { Storage } = require("@google-cloud/storage");

const storage = new Storage({
    keyFilename: "/path/to/key/file.json",
});

The key file in question is the "Private Key" generated in "Service accounts" under "Settings".

I then try to access the file as follows

storage
    .bucket("my-bucket")
    .file("test.txt")
    .createReadStream()
    .on("error", (err) => res.status(500).send("Internal Server Error"))
    .on("response", (storageResponse) => {
        res.setHeader(
            "content-type",
            storageResponse.headers["content-type"]
        );
        res.setHeader(
            "content-length",
            storageResponse.headers["content-length"]
        );
        res.status(storageResponse.status);
    })
    .on("end", () => res.end())
    .pipe(res);

The file "test.txt" is located in the root folder of the storage, and "my-bucket" is the one used in the bucket link "gs://my-bucket.appspot.com".

When console.logging the storageResult, I get

statusCode: 404,
statusMessage: 'Not Found'

And

href: 'https://storage.googleapis.com/storage/v1/b/my-bucket/o/test.txt?alt=media'

Shouldn't there be a token attached to it? This link does point to a "Not Found" page...

Any thoughts on why this doesn't work?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like you are missing project id when initializing Storage client, project id doesn't seem to be set by default in environment variable.

Try this:

const storage = new Storage({"projectId", "/path/to/key/file.json"});

as described in the docs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...