Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to get file link from google cloud storage using Node.js ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

To get the signed public link of a file from the Firebase storage, we need a reference to the file in Google Cloud storage. As we just have a path to that file in storage we would first need to create a reference to that object and then get a signed link to that file.

Steps to generate a public link to a file in storage using the file path:

  • Get the reference to the storage using a bucket() and file() methods on the storage object from @google-cloud/storage.
  • Generate a signed public link for that file using the getSignedUrl method on the reference object created in the first step.

Module Installation: Install the module using the following command:

npm install @google-cloud/storage

The method getSignedUrl() tasks a config object as input and returns a Promise that resolves with the download URL or rejects if the fetch failed, including if the object did not exist.

Example: Filename: index.js 

Javascript




// Imports the Google Cloud client library
const { Storage } = require('@google-cloud/storage');
 
// Creates a client
const storage = new Storage();
 
const bucketName = 'geeksforgeeks';
const fileName = 'gfg.png';
 
// Create a reference to the file to generate link
const fileRef = storage.bucket(bucketName).file(fileName);
 
fileRef.exists().then(function (data) {
    console.log("File in database exists ");
});
 
const config = {
    action: 'read',
 
    // A timestamp when this link will expire
    expires: '01-01-2026',
};
 
// Get the link to that file
fileRef.getSignedUrl(config, function (err, url) {
    if (err) {
        console.error(err);
        return;
    }
 
    // The file is now available to
    // read from this URL
    console.log("Url is : " + url);
});

Run the index.js file using the following command:

node index.js

Output: 

File in database exists 
Url is : https://storage.googleapis.com/geeksforgeeks/gfg.png?X-Goog-Algorithm=[token]
My Personal Notes arrow_drop_up
Last Updated : 05 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials