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
199 views
in Technique[技术] by (71.8m points)

node.js - Download File on Request in Firebase

I am looking for a solution to directly download a file in the Firebase Storage when hitting an API endpoint. I tried initializing a Google-Cloud Storage and downloading the file from the bucket.

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

const storage = new Storage({keyFilename: keyPath});

app.get("/download", (req, res) => {
    storage.bucket(bucketName).file("file.txt").download({destination: './file.txt'});
});

app.listen(8080);

But this does not work!

I simply get:

UnhandledPromiseRejectionWarning: Error: Not Found

Could someone help me, please?


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

1 Answer

0 votes
by (71.8m points)

Where did you initialize the app

Original answer:

// Dependencies
const express = require('express')

const PORT = process.env.PORT || 3002;

// Initialize the App
const app = express();

// Start the app
app.listen(PORT, () => {
    console.info(`Server is listening on port ${PORT}`);
});

Update: Making HTTP requests to download files is an asynchronous operation. You need to wait for the file to be downloaded from the Google Cloud Storage before sending it to the client

const app = require('express')();
const { Storage } = require("@google-cloud/storage");
const storage = new Storage({keyFilename: keyPath});

// I am using async/await here
app.get("/download", async (req, res) => {

// You have to wait till the file is downloaded
    await storage.bucket(bucketName).file("file.txt").download({destination: './file.txt'});
// Send the file to the client
res.download('./file.txt')
});

app.listen(8080);

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

...