Retrieve the sibling files of a newly created file within a Firebase Cloud Function that is triggered by the onFinal

I'm in need of some guidance with a cloud function I have set up that triggers whenever a new file is created in Firebase storage. Within this function, I am looking to gather all other files located at the same path and store them in an array. However, this task has proven to be a challenge for me.

exports.testCloudFunc = functions.storage.object().onFinalize(async object => {
  const filePath = object.name;

  const { Logging } = require('@google-cloud/logging');

  console.log(`Logged: ${filePath}`);
  let obj = JSON.stringify(object);
  console.log(`Logged: ${obj}`);
});

My ultimate goal is to combine all PDFs found into a single new file, which will then be saved back to Firebase storage using the same path. Any assistance or words of wisdom on how to achieve this would be greatly appreciated! Thank you in advance!

Answer №1

Based on the information provided by the documentation referenced by Doug Stevenson in the second code example for Node.js, you have the ability to retrieve a list of objects from a specific folder within your bucket using designated prefixes and delimiters.

Here's an excerpt from the mentioned documentation:

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const prefix = 'Prefix by which to filter, e.g. public/';
// const delimiter = 'Delimiter to use, e.g. /';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function listFilesByPrefix() {
  /**
   * This can be used to list all blobs in a "folder", e.g. "public/".
   *
   * The delimiter argument can be used to restrict the results to only the
   * "files" in the given "folder". Without the delimiter, the entire tree under
   * the prefix is returned. For example, given these blobs:
   *
   *   /a/1.txt
   *   /a/b/2.txt
   *
   * If you just specify prefix = '/a', you'll get back:
   *
   *   /a/1.txt
   *   /a/b/2.txt
   *
   * However, if you specify prefix='/a' and delimiter='/', you'll get back:
   *
   *   /a/1.txt
   */
  const options = {
    prefix: prefix,
  };

  if (delimiter) {
    options.delimiter = delimiter;
  }

  // Lists files in the bucket, filtered by a prefix
  const [files] = await storage.bucket(bucketName).getFiles(options);

  console.log('Files:');
  files.forEach(file => {
    console.log(file.name);
  });
}

listFilesByPrefix().catch(console.error);

  

Could it be that initially all files are retrieved and then filtered based on the prefix?

The code snippet above indicates that the array [files] will contain the objects that meet the specified filter criteria:

const [files] = await storage.bucket(bucketName).getFiles(options);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I display a clicked-on div while hiding all other divs using jQuery?

I want to create a website where a button can show and hide a specific div, but my challenge is; How can I ensure that clicking on one button hides all other divs? Here is the JavaScript code: function showHide(divId){ var theDiv = document.getEleme ...

Occasion that fires prior to the DOM being fully loaded

Is there an event in my Firefox extension that triggers before DOMContentLoaded and allows me to insert HTML while the document is still available? ...

Struggling with accessing data from an array of objects in JavaScript?

Trying to create a program that takes user input from HTML forms and organizes it into objects for each user. I have set up an HTML form, created a constructor, added a click event to generate the object, saved it in a variable, and attempted to place that ...

Effortlessly transfer files with Ajax through Box

I attempted to utilize the Box.com API for file uploads according to instructions from https://gist.github.com/seanrose/5570650. However, I encountered the following error message: `XMLHttpRequest cannot load "". No 'Access-Control-Allow-Origin&ap ...

In JavaScript, use regular expressions to replace every instance of a link with its corresponding href object (map link -> a href=link)

I am looking to replace the following text: "wjjghwkjghwkjgh https://www.google.com jhgkwjhgkwhgk https://youtube.com" with: "wjjghwkjghwkjgh <a href='https://www.google.com'>https://www.google.com</a> jhgkwjhgkwhgk <a href=&a ...

Is it possible to toggle the status of an item in JSON based on a counter value

Here is the JSON data I have: "questions": { "id": 1, "question": "Select one color", "answers": [ {"id": 1, "answer" : "Green", "isSelected" : false}, {"id": 2, "answer": "Red", "isSelected" : false}, ...

In Angular, when a promise returns an "undefined" value, how does this interact with .NET

When I execute this code snippet, I am encountering an issue where the response returned is "undefined" instead of the expected value. Here is the code in question: $scope.SameNameFunction = function() { var payload = { itemname: $scope.EventD ...

Tips for synchronizing arrays using the Angular Drag-Drop Component

My drag and drop component in HTML looks like this: <div class="example-container flex flex-col text-center h-fit min-h-[10rem] w-[15%] border-2 border-gray-100 rounded-md shadow-md" > <h2 class="text-xl font-semibo ...

What is the option for receiving automatic suggestions while formatting components in a react.js file?

When styling elements in our app using app.css or styles.css, VS Code provides auto-suggestions. For example, if we type just "back" for background color, it will suggest completions. However, this feature does not work in react.js or index.js. Why is that ...

Is it possible to use VueJS (JavaScript) to submit a form within a PHP file?

Recently, I've been working on updating an old PHP file that includes a form and a table. The code snippet below gives an overview: printf ("<form action=\"%s\" method=post>", $PHP_SELF); //this is the url printf (& ...

Resolving problem with saving an Array of Objects due to parsing issues with empty objects

I'm experiencing a peculiar problem with the Parse .save method. Saving individual Objects and Arrays of strings works seamlessly. However, when attempting to save an Array of Objects like: [{"pos": 10101, "id": 2312}, {...}, {...}], I encounter issue ...

Utilize service worker in Vue 3 to intercept img src and incorporate an Authorization header

Is there a way to display a private image through Laravel, which is functioning as an API and requires an Authorization header with a Bearer token? I am currently using Quasar, but I don't think that's relevant (unless Quasar offers a solution) ...

Storing the order of jQuery UI Sortable in the WordPress Admin Panel

My goal is to customize the order of taxonomy terms for each individual post in Wordpress. I have created a metabox on the EDIT POST page that contains custom taxonomy terms and made them sortable using JQuery. Here is my setup on the Wordpress backend: ...

How to position button components at the center in a NextJS application?

Incorporating a button within my nextjs page has been a challenge as I am striving to position it in the center of the page for optimal viewing on both PCs and mobile devices. Despite various attempts, the button remains fixed on the far left side of the p ...

Event Stencil Emitter Unclear

I am in the process of developing a web component using stencil and react. The issue I am facing is that even though the value is emitted, it appears as undefined when called within the component. @Event() newModuleClicked: EventEmitter<any>; ...

Is there a way to flip a figure that is flipped upside down?

I'm currently working on creating a map using a json file to go from d3.js to Three.js. However, when the map is displayed, it appears upside down. I'm wondering if there is a way to flip it so that it displays correctly. As a newcomer to d3 and ...

Node.js fails to provide AngularJS with JSON response

I am encountering an issue with establishing a REST connection between my node middleware and Angular UI. Instead of routing the JSON through the angular controller/html, it is being displayed directly on the browser. Here's my Node/Express router.js ...

Adjusting Font Size on a Website: A Quick Guide

I recently started diving into the world of building web pages. To practice, I created a simple site but for some reason, I'm having trouble changing the text size. When I try to remove the background image code, it seems to work fine, but I can&apos ...

Use Vue JS to send a GET request to the server with custom header settings

When creating a Vue.js component, I want to send a GET request to a server with specific headers. How can I achieve this? Using cURL: -X GET "http://134.140.154.121:7075/rest/api/Time" -H "accept: application/json" -H "Authorization: Bearer eyJhbGciOiJSUz ...

Module '../../third_party/github.com/chalk/supports-color' not found in the directory

Within my tutoring-frontend-main project folder There is a file named package.json { "name": "app-frontend", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build --prod", "test": "n ...