Managing large datasets effectively in NestJS using fast-csv

Currently leveraging NestJS v9, fast-csv v4, and BigQuery for my project.

  1. Controller (CSV Upload):

@Post('upload')
@ApiOperation({ description: 'Upload CSV File' })
@ApiConsumes('multipart/form-data')
...
// Code shortened for brevity
  return await this.filesService.uploadCsv(file, uploadCsvDto);
}

  1. Service Logic:

async uploadCsv(
...
// Code shortened for brevity
  console.log(`Inserted ${rows.length} rows`);
  ...
}

// More service functions not shown here
...

export function memoryUsage(): void {
 return console.log(
  `APP is using ${
    Math.round((process.memoryUsage().rss / 1024 / 1024) * 100) / 100
  } MB of memory.`,
 );
}

  1. Explanation of Service Process:
  • Initial check in BigQuery for duplicates from previous CSV uploads.
  • Utilization of stream (fast-csv) to avoid loading all CSV data into memory at once.
  • ... // Details on processing every 200 rows and saving batches into BigQuery ...

Issue: Encounter memory problems when handling larger files above 50,000 rows:

50,000 row CSV example:

250,000 row CSV example:

Unable to identify why the memory issues persist even after clearing unnecessary variables.

Current node server indicates a maximum memory size of 512MB.

Memory Checking Function Used:

export function memoryUsage(): void {
 return console.log(
  `APP is using ${
    Math.round((process.memoryUsage().rss / 1024 / 1024) * 100) / 100
  } MB of memory.`,
 );
}

Answer №1

If you're facing difficulties with this issue, I have a solution. Simply break down the buffer from the CSV file into smaller chunks.

Here is an example:

const ROWS_BATCH = 200;
const blockSize = 100 * 100 * 100; // 0.9537 MB.
const csvHeaders: string[] = [];
let offset = 0;

// 1. Chunk buffer, 2. Chunk rows, 3. Chunk insertions into BigQuery
while (offset < buffer.length) {
  const remainingBytes = buffer.length - offset;
  const currentBlockSize = Math.min(blockSize, remainingBytes);
  const chunk = buffer.slice(offset, offset + currentBlockSize);

  const streamFromBuffer = Readable.from(chunk);
  // rest of code ...
}

This way, you don't need to load the entire buffer into memory at once. Instead, you can load it in manageable chunks.

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

Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can ...

Here's a guide on using a button to toggle the display of password value in Angular, allowing users to easily hide

I have successfully implemented an Angular Directive to toggle the visibility of password fields in a form. However, I am facing an issue with updating the text displayed on the button based on the state of the input field. Is there a way for me to dynami ...

Ways to leverage ember.js in a serverless environment

After checking out the example of ember.js on this website (http://todomvc.com/), I decided to clone the project onto my computer. Upon double-clicking the index.html file, the project ran smoothly, just as I had anticipated. However, following the instru ...

Having trouble with Firebase continuously replacing old images with new ones whenever I upload them using JavaScript/jQuery

I am experiencing an issue with Firebase where it overrides my old pictures every time I upload a new picture. How can I configure it to save my old pictures as well? <!DOCTYPE html> <html> <head> <title>Firebase Storage< ...

Highlighting a Table Column with a Radio Button

I am struggling with controlling the highlight of a table using only radio buttons. When I try to change the selector to input:radio, it doesn't work as expected. It seems to only work with the selector provided in my code snippet. $("th").on("clic ...

Is it not possible to generate HTML tags using jQuery and JavaScript in JSF?

I'm currently working with jsf 2.0 and richfaces 4.0 to develop my application. Occasionally, I incorporate jQuery and JavaScript functions for displaying and hiding elements. However, I've encountered an issue when trying to generate tags within ...

Address Book on Rails

Hello, I'm relatively new to this and would be grateful for any assistance. My goal is to utilize the data saved by a user in their address book, and then offer them the option to use that address for delivery. Below is my Address controller: class A ...

Unable to locate the accurate information

Every time I run the cycle, there should be a match with the specified parameters and the message "OK" should appear. However, I am always getting a result of "No". request( { url: 'http://localhost:5000/positions/get', metho ...

"What is the best way to transform tab navigation into a dropdown menu with the help

I have a collection of tabs currently on display. I am looking to transform them into a dropdown menu when the screen size changes, making them more responsive. Each set of tabs corresponds to different content. Despite trying various solutions found on s ...

Transmit information using JSON format in Angular 8 using FormData

i am struggling with sending data to the server in a specific format: { "name":"kianoush", "userName":"kia9372", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcd7d5ddd8ce85...@example.com</a>" } H ...

Ways to extract data from an array nested within a JSON object

I am seeking guidance on how to access the value of "result 2" from my JSON object using jQuery or pure JavaScript. var jsonarray = [{ title: "Category1", items: [{ result: "Item1", //Nested array items2: [{ //How to get the value o ...

Divide JSON arrays into separate select boxes

I have integrated AngularJS into certain sections of my website, rather than using it for the entire site. Currently, I am dealing with a scenario where I have a pair of select boxes, one dependent on the other. One box contains a list of countries, while ...

Calculate the total of all values associated with a dynamically generated key within an array of objects

I'm trying to calculate the sum of similar keys in an array of objects. Each object in the array will have some common keys, but not all arrays will share the same set of keys. I'm considering storing these keys in a separate array and then loopi ...

Maintaining checkbox state using fetch arrays

Included below is the code present on my site, pulling data for each season including numbers of home wins, win percentage, and win lsp. It functions correctly by creating a new table row for each season. Furthermore, there are two columns featuring filte ...

The MDBDataTable features header sections at both the top and bottom, but the filters UI seems to be

Currently, I am working with MDBDataTable and encountering an issue with the double heading that appears both on top and bottom of the table. I am unsure how to remove it. The code snippet in question is as follows: There is a function that retrieves and ...

Events triggered by JQueryUI's .selectable functionality

I am facing a minor issue with the JQuery .selectable function. My goal is to bind events to each tab. I have successfully handled the click event for each tab, but I'm struggling when it comes to selecting two or more tabs. For instance, if I clic ...

Using Express.js with Pug.js, dynamically render the page with new content following a fetch POST request

I have a collection of article previews sourced from a database and rendered on the webpage using a Pug.js mixin. each article in articles +articlePreview(article.title, article.text, article.imgSrc) To enhance the user experience, I want to implem ...

Switch up a font style using JavaScript to apply a Google font effect

I am attempting to implement a discreet hidden button on a website that triggers a unique Google font effect for all of the h1 elements displayed on the page. However, I am uncertain about the process and unsure if it is achievable. Below is the code snipp ...

How to Enhance Angular ui-router nested views with Resolve?

I have been working on creating a customized version of my Angular 1.4.12 application with nested views. The main purpose behind this customization is to accommodate sections within the app that require a header/content/footer structure, while others do no ...

Is it possible to adjust the CSS code linked to the HTML tag based on the specific webpage being viewed?

I am facing an issue with the homepage of my website, which uses Scrollmagic.js for smooth scrolling. In order for the sticky footer CSS to work properly on all other pages, the HTML tag needs to have a height of 100%. However, if I add this height value t ...