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

Is there a way to instruct Google to include my site in its index using Angular.js?

I am currently working on an angular.js app and have been following Google's guide for ajax-based applications. Here are the steps I have taken: Added meta tags <base href="/"> <meta name="fragment" content="!"> Configured angular.js ...

Having trouble displaying image using absolute path in Express

Currently, I am developing a NodeJS application and have encountered an issue with a div element that has a background-image set in an external CSS file. Surprisingly, the CSS file functions perfectly when tested independently, and the background image dis ...

Exploring Amcharts using detailed JSON data

[{"SUM_PTS":{"datatype":"INTEGER","length":"8","value":"29903727","obfuscated":"false"},"SUM_TOTAL":{"datatype":"INTEGER","length":"10","value":"1644704985","obfuscated":"false"},"MID":{"datatype":"ALPHANUMERIC","length":"27","value":"Vendor 1","obfuscated ...

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) ...

Inject nested controller dynamically

I am working on a straightforward ASP.NET MVC application that includes an ng-controller. I am trying to inject another ng-controller inside this controller using a partial view, but I'm having trouble getting the binding to work correctly. You can s ...

Having issues with clicking on a row in the table while using AJAX functionality

Experiencing a puzzling issue while attempting to add click functionality to table rows with AJAX, here is the JavaScript code used: //for tabs $(document).ready(function () { $("#tabs").tabs(); }); $(window).load(function() { jsf.ajax.addOnEven ...

Determine if a specific value is present in an array of objects using AngularJS

var arr = [ { id:1}, {id:2} ]; var obj = {id:1}; var result = arr.indexOf(obj.id) == -1; console.log(result); I am trying to determine if obj.id exists in the array arr[]. Please note: arr[] is an array of objects ...

What is the process for encrypting and decrypting image files over the internet?

I'm currently developing a web application that requires loading images into a canvas object, followed by extensive manipulation. My goal is to conceal the original source image file (a jpeg) in such a way that users on the client side cannot access i ...

Jumbling a word by shuffling its letters into a random order

The objective of the program is to take the word you input into a box, split it into an array of letters, and then shuffle them. Following that, it should capitalize the first letter and lowercase the rest before displaying the result in the same box. I a ...

After checking the checkbox to add a class, I then need to remove that class without having to interact with the entire document

When I click on a checkbox, an animation is added to a div. However, I am struggling to remove this animation unless I click elsewhere on the document. The goal is for the checkbox to both add and remove the class. JS $('#inOrder').click(functi ...

Incompatibility issues arise when trying to implement Dojo toolkit widgets in an AngularJS application

I'm currently working on integrating Dojo gauges into my AngularJS application. I know that Dojo is also a framework that follows the MVC pattern like AngularJS, but right now, I have an AngularJS app and I want to utilize existing widgets from other ...

Sorting an array of numbers using Javascript

Does anyone know how to properly sort an array in JavaScript? By default, the sort method doesn't work efficiently with numbers. For example: a = [1, 23, 100, 3] a.sort() The sorted values of 'a' end up being: [1, 100, 23, 3] If you hav ...

Modifying website elements with JavaScript

Can someone assist me with getting a script to work on my website that will allow me to switch between four different sets of content using buttons labeled 1, 2, 3, and 4? I have tried using addClass and removeClass but cannot seem to get it right. Here i ...

Encountering a TypeError when attempting to read the property 'name' of undefined while submitting a form in node.js

I'm currently working on a node Js project and I'm encountering an issue while saving form values to a mongoDB database. I've been troubleshooting but can't seem to pinpoint the cause of this error. The error is occurring at the router. ...

Oops! The Route post function is missing some necessary callback functions, resulting in an undefined object error

I need to verify if a user has admin privileges. Every time I try calling the verifyAdminUser function from my router, I encounter the following error: Error: Route.post() requires callback functions but got a [object Undefined] at Route.(anonymous func ...

Turn off auto-suggestion feature on the iPad and iPhone keyboard using JavaScript

I'm facing a challenge where I want to turn off the predictive suggestions and autocorrect feature on the iPad keyboard. This image is just for display purposes and not from my actual project. I need to hide the highlighted suggestion bar, and I am u ...

Display the count of ng-repeat items beyond its scope

Currently, I am looping through a list of nested JSON objects in this manner: <div ng-repeat='item in items'> <ul> <li ng-repeat='specific in item'>{{specific}}</li> </ul> </div> I want to ...

The product image does not display any other images

Hey, I'm experiencing an issue and need help replicating the photo changing effect on this website: I've managed to do everything right except for the photo changing feature (1 / 2 / 3 / 4)!! Here's what I have so far: Can anyone assist m ...

React State Update Triggered by Changing Hidden Input/Textarea Value - No User Input Required

To activate a function when the contents of a hidden input, textarea, or textfield change in React without requiring user input to trigger it, you will need to dynamically adjust the value of the hidden input and then have the function automatically exec ...

Having trouble deciding between flatMap and concatMap in rxJs?

Having trouble grasping the distinction between flatMap and concatMap in rxJs. The most enlightening explanation I found was on this Stack Overflow post about the difference between concatMap and flatMap So, I decided to experiment with it myself. import ...