Creating a structured file hierarchy by extracting files from Amazon S3 and transferring them for storage in Firebase

I am looking to retrieve key/value pairs from Amazon S3 and then store some of the obtained information in Firebase to build a file system in AngularJS.

This question focuses only on storing in Firebase.

It is essential to be able to create an unlimited number of folders and files within those folders. However, my current code structure requires adding IF/ELSE statements every time I want to add a subfolder. I need a more dynamic solution.

In AngularJS, I have developed a script that fetches Key/Value pairs from Amazon S3 and stores them in Firebase based on the returned Key.

To explain the process, I have divided the code into sections but you can view the entire block on this jsFiddle link: https://jsfiddle.net/Lcr5p6qm/2/

Firstly, I extract the key/value pairs from Amazon using a service.

storageService.getBucketDirectory({
   'bucket' : bucket,
   'directory' : 'code/'
}).then(function(code){

Secondly, I remove the existing tree from Firebase and loop through each key/value pair from S3.

projectRef.child('code').remove();
angular.forEach(code, function(value, key){

   var item = value.Key.replace('code/', '');

Thirdly, if the pair represents the base level, we handle it accordingly by altering the key to define a type and name for the file.

if(!item.includes('/'))
{

    var name = value.Key.replace('code/', '').replace('/', '').replace('+', ' ');

    if(name.indexOf('.') == 0)
    {
       var type = null;
    }
    else
    {
       var type = value.Key.substr(value.Key.indexOf('.') + 1)
    }

    projectRef.child('code').child('/').push({
       'Name'           : name,
       'Type'           : type,
       'Key'           : value.Key,
       'LastModified'  : value.LastModified,
       'Size'           : value.Size
    })
}

Next, we handle pairs that are not at the base level and may contain subfolders in the key structure. We modify the key and store it accordingly with or without subfolders.

else {
  var folder = item.substr(0, item.indexOf('/'));

  if ((item.replace(folder + '/', '')).includes('/')) {
    var subfolder = item.replace(folder + '/',');

    subfolder = subfolder.substr(0, subfolder.indexOf('/'));
    
    var name = value.Key.replace('code/','').replace(folder+'/','').replace(subfolder+'/','').replace('+','');

    if (name.indexOf('.') === 0) { 
        var type = null; 
    } else { 
       var type = value.Key.substr(value.Key.lastIndexOf('.') + 1);
    }

    projectRef.child('code').child(folder).child(subfolder).push({ 
     'Name': name, 
     'Type': type, 
     'Key': value.Key, 
     'LastModified': value.LastModified, 
     'Size': value.Size 
    }) 
  } 
  else { 
    //store in folder directly 
    var name = value.Key.replace('code/','').replace(folder+'/','').replace('+','');
   
    if (name.indexOf('.') === 0) {
      var type = null;
    } else {
      var type = value.Key.substr(value.Key.indexOf('.')+1); 
    }

    projectRef.child('code').child(folder).push({ 
     'Name': name, 
     'Type': type, 
     'Key': value.Key, 
     'LastModified': value.LastModified, 
     'Size': value.Size 
    }) 
  } 
} 

Ultimately, this results in something like the following folder structure.

  • css
    • main.css
    • normalize.css
  • doc
    • TOC.md
    • css.md
    • extend.md
    • faq.md
    • html.md
    • js.md
    • misc.md
    • usage.md
  • img
    • .gitignore
  • js
    • main.js
    • plugins.js
    • vendor
      • jquery-1.12.0.min.js
      • modernizr-2.8.3.min.js

While this structure works, it has limitations when more than second-level directories are required. The issue arises when there is another folder within the /js/vendor/ folder as it breaks the system by incorporating the subfolder name into the file properties. I need a way to support an infinite number of sub-folders.

UPDATE

I have refined the code in my JSFiddle under "Second Attempt". Although it gets closer to the desired functionality, it still does not fully accommodate additional subfolders.

Bonus: What about empty folders?

Answer №1

In Firebase, you can use a path-like string as the parameter for .child(). This means you only need to focus on manipulating the key string to extract the path and filename. To achieve this, you can implement the following steps:

var sampleKey = 'folder/another/subdirectory/filename.doc';

var lastSlashIndex = sampleKey.lastIndexOf('/');

var directoryPath = sampleKey.substring(0, lastSlashIndex); // 'folder/another/subdirectory'
var fileTitle = sampleKey.substr(lastSlashIndex + 1);  // 'filename.doc'

projectReference.child(directoryPath).push({
    'Title': fileTitle
});

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

Modify the state from a listener that is enclosed in the useEffect function

Within my hook called useQueryEvents, I have a setup that involves fetching all past transactions for a user and listening to the network for incoming/outgoing transactions. These transactions are then passed into a function called addActionToActivity, whi ...

The functionality of onClick and console.log seems to be malfunctioning on Nextjs

I'm currently learning NEXT but I've encountered some issues with certain functions "use client" import { useState } from 'react' export default function idk() { const [counter,setCounter]=useState(0) const add=()=> ...

Searching for files in directories and subdirectories using Node.js

Although I found this solution, it seems to be quite slow. I am looking for the quickest way to traverse directories without using npm packages. Any suggestions? ...

Ben Kamens has developed a new feature in jQuery Menu Aim where the sub menu will not reappear once it

While exploring Ben Kemens’ jquery-menu-aim, I came across a demonstration on codepen. The code on codepen allows smooth transition from the main menu to the sub menu, but if you move away completely, the submenu remains visible and doesn't disappe ...

Adjusting the font color when hovering over multiline text

I am currently in the process of coding a website for my job, and I am working on changing the text color when it is hovered over. However, there seems to be a break in my code causing the text not to highlight all at once. Any guidance or suggestions on h ...

Every time a button is clicked on the interface, a new element or button will appear. This functionality is made possible through

Currently diving into a new React.js project as a beginner. I have a little challenge in the code snippet below - looking to add a button that displays "Hello World" every time it's clicked using setState. Can anyone guide me on enhancing the DisplayM ...

jQuery - How come my string values are getting cut off?

It's been a while since I last worked with jQuery, and I seem to be missing something obvious that's affecting my calculations. I have various text boxes for Weight, Moisture %, and Number of Filled Squares, as well as a multi-select option for ...

Update the div on the current page using externally retrieved information

Once again, I find myself stuck on a problem. Allow me to explain. Within this div, I have retrieved data using HTML SIMPLE DOM from another site. Like so: <div id="data">.....</div> Currently, the data refreshes whenever the user reloads th ...

Registering directives dynamically during runtime

Typically, directives are added to a module by calling the directive method: .directive('MyDirective', function (MyDep) { return { restrict: 'E', template: '<div></div>', controller: fu ...

Ensure the presence of an editable column within a table using a jQuery function

Within the table, the first column is editable. Upon making a change to it, I want an alert to appear indicating that a change has occurred. The check function is being called after a delay of 5000ms. Embedding Code Snippet for Reference I suspect there ...

Guide on downloading a PDF file with NodeJS and then transmitting it to the client

My goal is to download a PDF file using NodeJS and then send its data to the client to be embedded in the page. Below is the code snippet I am using to download the PDF file: exports.sendPdf = function(req, responce) { var donneRecu = req.body; va ...

Making requests using Axios in a web application created with Express, Node, and EJS

I'm currently working on a project that involves using Express.js, node.js, Axios, and ejs. The aim is to make REST calls to Oracle SQL REST services through Axios. However, I am facing challenges when it comes to dealing with Promises or Async/Await. ...

Utilizing styled-components or personalized components alongside cypress

Cypress selector made simple: just use cy.get('.myComp') and it will select <input className="myComp" />. But when it comes to styled-components... Perhaps we have to resort to using custom attributes like cy-data or cy-testid. Sadly, it s ...

Unable to process the post request

I've encountered an issue while attempting to redirect using the res.redirect() function. When I submit the form, it should insert the data into the database and then redirect me to the home root. However, instead of successfully redirecting, I'm ...

Adjusting the width of the final card in the deck grid

Currently, I am utilizing angular-deckgrid for image display purposes. Within a container, there are two columns in which images are displayed with the column-1-2 class according to the documentation. However, in certain scenarios where only one image is p ...

AngularJS - Hiding Elements Dynamically Using `ng-hide` Based on an

Is it possible to create an inline expression for ng-hide in the following manner: ng-hide="userType!=user" Please advise on how to achieve this. ...

Encountering difficulties when trying to display a nested object with two levels of depth using

I am currently developing an application where I need to display a nested object with two levels using the map method. The data structure is as follows: const categories = [ { catName: "Education", subCategory: [ { subCatName: "Col ...

What is the process by which browsers manage AJAX requests when they are made across

I have encountered an issue that is puzzling to me, and I suspect it might be due to my misunderstanding of how the browser handles AJAX requests. Just for context, I am using Codeigniter on an Apache server and triggering AJAX requests with jQuery. The b ...

Display HTML content repeatedly depending on the number selected in a dropdown menu using AngularJS

I need your assistance with a dropdown selection feature on my website. The idea is that based on the number chosen from the dropdown, I want to dynamically repeat sections in HTML. For example, if I select 3 from the dropdown menu, the page should display ...

Getting some clarity on how to structure a project using Node.js, Express.js, and React.js

I am in the process of developing a website for online shopping purposes, essentially an e-commerce platform. However, I am facing a dilemma where create-react-app sets up its own Node.js server to communicate with my backend (which handles MySQL queries) ...