The issue of JavaScript Memory Leakage when utilizing FileReader and Promise

-Modify

I have raised a bug report to address this issue


I am attempting to upload a directory to my server containing large files, including CT scan images. While the process is functioning correctly, I am encountering memory problems.

document.getElementById("folderInput").addEventListener('change', doThing);

function doThing(){
    var filesArray = Array.from(event.target.files);

  readmultifiles(filesArray).then(function(results){
    console.log("Results read :" + results.length);
  })
}

function readmultifiles(files) {
  const results = [];
  return files.reduce(function(p, file) {
    return p.then(function() {
      return readFile(file).then(function(data) {
        // store the result in the results array
        results.push(data);
      });
    });
  }, Promise.resolve()).then(function() {
    // ensure final resolved value is the results array
    console.log("Returning results");
    return results;
  });
}

function readFile(file) {

  const reader = new FileReader();

  return new Promise(function(resolve, reject) {
    reader.onload = function(e) {
      resolve(e.target.result);
    };
    reader.onerror = reader.onabort = reject;
    reader.readAsArrayBuffer(file);
  });
}

View JSFiddle of the proposed solution - Utilizing response from this query

In the provided example, no action is taken with the data but there is observed growth in memory usage.

Memory consumption prior to uploading:

Memory consumption post-upload:

The uploaded file folder is 342Mb which explains the increase in memory, however, it should be released afterwards, right?

If you have any suggestions on how to overcome this issue or if there is an alternative API that could be utilized instead of FileReader, please share your insights.

MODIFY-----

I suspect this is a Chrome and V8 related bug. Upon testing with Firefox, the memory is properly freed. It could be associated with this reported bug

Answer №1

If you want to optimize your code, try removing any instances of the FileReader objects after using them. Instead of creating multiple readers in a loop and leaving them in memory, create one, use it, delete it, then repeat the process as needed.

By setting these objects to null, they will eventually be garbage collected, freeing up memory in your application.

Tip:

Try declaring the reader inside a Promise handler to ensure automatic garbage collection.

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

What is the purpose of including a function in an AngularJS dependency array?

When it comes to injecting dependencies, the process involves the following steps: inject(["$scope", "$compile", function ($scope, $compile) { ... }]); The syntax used here may seem strange. Placing the function inside the array might appear counter-in ...

Turning a JSON dot string into an object reference in JavaScript: A simple guide

Having a JSON object labeled test with values like this: {"items":[{"name":"test"}]}, I need a way to apply the string items[0].name to it in order to search for a specific value (test.items[0].name). Currently, my only idea is to create a function that pa ...

Having difficulty transforming ".jsx" to ".tsx" in a Next.js application while working with "getStaticProps"

My application utilizes the Printifull API and performs well with .jsx using the code snippet below: import axios from "axios"; export default function ApiTest(props) { console.log(props); return( <></> ( } export async ...

AngularJS: Issues with data retrieval in parallel in $http get requests within a $.each loop

Attempting to fetch data for multiple IDs is the goal: (Simplified version, aiming to clarify) Controller: var idList = [39,40,41]; $.each(idList, function(key, value){ var dataObject = { type: "test", id: value }; var getData = DataFactor ...

How can I animate scrolling up or down using jQuery and CSS?

I have a a element that triggers an action when clicked: <a href="#" class="hel" onclick="YPCP1_();">Scroll down</a> Also, function YPCP_(){ var scroll = $(window).scrollTop(); window.scrollTo(0, 600); } The function successfully sc ...

How to activate a single element within a React array

I am currently working on developing a comment system similar to the one found on YouTube. In my setup, when I click on modify, all comments turn into input fields, but only the selected input should be modified. How can I trigger only the element I clicke ...

Is it expected to conceal children who are 2 years old?

I came across the following HTML code snippet: <ul id="product_create-header" class="stepy-header"> <li id="product_create-head-0" class="stepy-active"> <div>Categoría</div><span>Categoría</span> </ ...

Error thrown: Upon attempting to reopen the modalbox after closing it, an uncaught TypeError is encountered, indicating that the function $(...).load

An unexpected error occurred: $(...).load(...).modal is not functioning properly After closing a modal, I encountered this error in the console when attempting to reopen it. Strangely, it seems to work intermittently for a few times before throwing this e ...

Guide to installing angular-ui-bootstrap through npm in angularjs application

My goal is to incorporate angular-ui-bootstrap into my project using the following steps: 1. npm install angular-ui-bootstrap 2. import uiBootstrap from 'angular-ui-bootstrap'; 3. angular.module('app', [      uiBootstrap    ]) I ...

completing data tables and presenting them to clients

I am currently working on a website for a Nutrition specialist who requires a monthly diet regimen table with five meals daily. The doctor will be responsible for completing these tables, which will then be presented to clients. It's important that th ...

Redux state assigns object to another object

I started with an initial state that looks like this: let initialState = { items: [ { name: 'a' }, { name: 'b' } ], otherItems: [] } I am attempting to copy the items array and assign i ...

Trouble with React component not updating after URL parameter change despite utilizing useEffect hook for data fetching

Let's address an important issue: I've created a component that needs to maintain the same structure across approximately 25 different items or pages. To achieve this in React, I am dynamically passing URL parameters into my API request as shown ...

Placing a JavaScript button directly below the content it interacts with

I am currently working on a button that expands a div and displays content upon clicking. I am facing an issue where I want the button to always be positioned at the bottom of the div, instead of at the top as it is now, but moving it within the parent div ...

What is the best way to remove empty elements from an Array?

Having an issue with my API post request. If no values are entered in the pricing form fields, I want to send an empty array. I attempted to use the filter method to achieve this but it still sends an array with an empty object (i.e. [{}]) when making the ...

Transform the text area in preparation for a GET request

Trying to figure out how to pass the text from a textarea into the source attribute of an image tag while retaining all formatting, including line breaks. After some research, it seems that the best way to accomplish this is by base 64 encoding the text a ...

Showcasing the time variance using javascript/jquery

I am currently using a datepicker to select dates, with the intention of calculating the difference between the chosen dates and then displaying an alert with the calculated difference. Unfortunately, I am encountering issues with getting the code to work ...

Remove a div element with Javascript when a button is clicked

I am working on a project where I need to dynamically add and remove divs from a webpage. These divs contain inner divs, and while the functionality to add new divs is working fine for me, I'm facing some issues with removing them. The code snippet b ...

Using jQuery to locate a JavaScript variable is a common practice in web development

I recently created a JSFiddle with buttons. As part of my journey to learn jQuery, I have been converting old JavaScript fiddles into jQuery implementations. However, I seem to be facing a challenge when it comes to converting the way JavaScript fetches an ...

store the id of each li element dynamically into an array

In my code, a list is generated dynamically and each list item has a special id. I am trying to store each li "id" in one array. This is JavaScript code: var i = 0; $("ul#portfolio li").each(function(eval) { var idd = new Array(); idd[i] = $(this ...

Adding a PHP file into an HTML page using JavaScript include

Recently, I was assigned to collaborate with a third-party vendor who displays movie times on their platform. We were given the opportunity to co-brand our website on their platform by creating a wrapper for our site. This wrapper would allow the movie tim ...