惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
K
Kaspersky official blog
T
The Exploit Database - CXSecurity.com
NISL@THU
NISL@THU
AWS News Blog
AWS News Blog
V2EX - 技术
V2EX - 技术
Google DeepMind News
Google DeepMind News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
Security @ Cisco Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recent Commits to openclaw:main
Recent Commits to openclaw:main
J
Java Code Geeks
Microsoft Azure Blog
Microsoft Azure Blog
Attack and Defense Labs
Attack and Defense Labs
Jina AI
Jina AI
The Last Watchdog
The Last Watchdog
W
WeLiveSecurity
H
Help Net Security
V
Visual Studio Blog
宝玉的分享
宝玉的分享
C
Cybersecurity and Infrastructure Security Agency CISA
T
Threat Research - Cisco Blogs
IT之家
IT之家
Hugging Face - Blog
Hugging Face - Blog
Latest news
Latest news
T
Tor Project blog
I
Intezer
美团技术团队
GbyAI
GbyAI
T
Tailwind CSS Blog
Last Week in AI
Last Week in AI
博客园 - 三生石上(FineUI控件)
Google DeepMind News
Google DeepMind News
Scott Helme
Scott Helme
Y
Y Combinator Blog
博客园 - 司徒正美
T
Tenable Blog
O
OpenAI News
N
News and Events Feed by Topic
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
V
Vulnerabilities – Threatpost
P
Palo Alto Networks Blog
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Threatpost
Google Online Security Blog
Google Online Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
云风的 BLOG
云风的 BLOG
Help Net Security
Help Net Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Processing a 2GB CSV in Node Without Running Out of Memory
Parthipan Natkunam · 2026-05-30 · via DEV Community

Why the obvious approach crashes, and how a few generator functions keep memory flat no matter how big the file gets.

Here's a task that looks trivial on paper: Read a CSV export, filter the rows you care about, sum one column, write a small report. The kind of thing you bang out in ten minutes. Now say the file is around 2GB.

The first version is four lines. It works great on a 5MB sample. Then you point it at the real export and Node falls over with JavaScript heap out of memory. The reflex is to do what most of us do first, bump --max-old-space-size, give it more heap, run it again. It gets further and dies again. That's the moment to stop fighting the symptom and look at what the code is actually asking the machine to do.

Here is the thing worth internalizing: the size of your data does not have to dictate the size of your memory footprint. You can process a file bigger than your RAM. The trick is to never hold the whole thing at once, and generators give you a clean way to write code that does exactly that without turning into a mess of callbacks and manual state.

Let's build up to it properly.

The version that dies

Here's roughly what the first attempt looked like:

const fs = require('fs');

const rows = fs.readFileSync('export.csv', 'utf8').split('\n');

let total = 0;
for (const row of rows) {
  const amount = Number(row.split(',')[2]);
  if (!Number.isNaN(amount)) total += amount;
}

console.log('total:', total);

Read the file. Split on newlines. Loop. Sum. Clean and readable, and on a small file it's perfect.

The problem is hiding in the first line, and it's actually two problems stacked on top of each other.

fs.readFileSync pulls the entire file into memory as one big buffer before you do anything with it. A 2GB file is a 2GB allocation, minimum. Then .split('\n') takes that buffer and produces an array with one string per line. For a file with millions of rows, that's millions of string objects, each with its own overhead, all alive at the same time. So now you're holding the raw file and a fully expanded array of every line. You've roughly doubled the cost of the thing that was already too big.

I wanted to see how bad it actually is, so I ran it. I generated a CSV with 2 million rows (id,name,amount), which came out to about 45MB. Modest. Not even close to 2GB. Here's what the load-everything approach did to memory:

naive sum: 999000000 | peak RSS MB: 238

238MB of resident memory to process a 45MB file. That's more than five times the file size sitting in RAM at peak. Now scale that ratio up. A 2GB file with the same shape would want somewhere north of 10GB, and your container almost certainly does not have that. Hence the crash.

What we actually want

Step back from the code for a second.

To sum a column, do you ever genuinely need every row in memory simultaneously? No. You need one row at a time. Read a line, pull out the number, add it to a running total, throw the line away, move on. At no point does row 1,400,000 need to coexist with row 3.

That's the whole insight. The work is sequential and one-pass, so the memory should be too. We want to pull rows through the program one at a time, like water through a pipe, instead of trying to fill an entire Ocean in a bucket.

Node has had streams forever, and streams do exactly this. But raw streams are awkward to compose. The moment you want to chain "read lines" into "parse them" into "filter them" into "sum them," you're wiring up event handlers and managing backpressure by hand, and the readable four-line version turns into something you don't want to look at.

This is where generators earn their place.

Generators, the one-paragraph version

A normal function runs start to finish and returns once. A generator function (the function* syntax) can pause itself partway through, hand a value back to whoever called it, and then resume from exactly where it left off the next time you ask for a value. It does this with yield.

For reading files we want the async flavor, async function*, because reading from disk is asynchronous. The consuming side uses for await...of instead of a plain for...of. Same idea, just async.

Building the pipeline

Let's write the big-file version as a set of small generators, each doing one job.

First, a generator that yields the file one line at a time. Node's readline module already reads a stream line by line, so we wrap it:

const fs = require('fs');
const readline = require('readline');

async function* readLines(path) {
  const rl = readline.createInterface({
    input: fs.createReadStream(path),
    crlfDelay: Infinity,
  });
  for await (const line of rl) {
    yield line;
  }
}

createReadStream reads the file in small chunks rather than all at once. readline hands us complete lines off those chunks. We yield each line as it arrives. Crucially, nothing is accumulating here. A line comes in, goes out, and is gone.

Next, a generator that turns raw lines into parsed objects:

async function* parse(lines) {
  for await (const line of lines) {
    const [id, name, amount] = line.split(',');
    if (id === 'id') continue; // skip the header row
    yield { id, name, amount: Number(amount) };
  }
}

Notice it takes a source of lines as its input and yields objects. It doesn't know or care whether those lines came from a file, a network socket, or an array in a test. It just transforms what flows through it.

Now a filter, because in this scenario, I only wanted rows above a threshold:

async function* onlyAbove(rows, min) {
  for await (const row of rows) {
    if (row.amount >= min) {
      yield row;
    }
  }
}

And finally we connect them and consume the result:

(async () => {
  const lines = readLines('export.csv');
  const parsed = parse(lines);
  const filtered = onlyAbove(parsed, 0);

  let total = 0;
  let count = 0;
  for await (const row of filtered) {
    total += row.amount;
    count++;
  }

  console.log('total:', total, 'count:', count);
})();

Read it from the inside out. readLines produces lines, parse consumes those and produces objects, onlyAbove consumes those and produces a filtered subset, and the for await loop at the bottom pulls the whole chain. Each stage is maybe five lines. Each one does a single thing. You can test them in isolation, reorder them, drop one in or out, all without touching the others.

Pipeline diagram with four generator stages feeding a for-await loop; forward arrows show data flow while dashed return arrows show the consumer pulling the next value upstream

Here's the part that matters. I ran this exact pipeline against the same 2 million row file:

pipeline sum: 999000000 count: 2000000 | peak RSS MB: 89

Bar chart showing peak memory of 238 MB for the load-everything approach versus 89 MB for the generator pipeline on the same 45 MB file

Same answer, 999000000, down to the last digit. But peak memory went from 238MB to 89MB. And that 89MB is not really "memory for the data." It's Node's baseline plus the read buffer plus a couple of objects in flight. The data itself is barely there because we only ever hold one row at a time. Throw a 2GB file at this and the number stays flat. That's the whole game.

Why this composes when streams alone don't

You might be thinking, fine, but Node streams could do this too, and you'd be right. So why the generators?

Pull versus push. A raw readable stream pushes data at you through events; you react to 'data' and 'end' and you manage the timing yourself. When you chain several transformations, you're coordinating several event emitters and making sure none of them races ahead of a slow consumer. Backpressure, in the jargon.

Generators flip it to pull. The consumer at the bottom of the loop asks for the next value, and that request travels back up the chain. onlyAbove asks parse for a row, parse asks readLines for a line, readLines asks the file for a chunk. Nothing is produced until something downstream wants it. Backpressure isn't something you configure; it's just how yield works. The producer literally cannot get ahead because it's paused until you call for the next value.

That's why the four small functions above read almost like the naive version, but behave like a carefully tuned stream. You get the readability of the simple loop and the memory profile of hand-written streaming, without choosing between them.

Where this bites you

I'd be lying if I said this is free.

The big one: you get one pass. A generator is exhausted once you've iterated it. If you need to loop over the data twice, say, sum a column and then also find the max in a separate pass, you can't just iterate the same pipeline again. It's empty the second time. You either compute both in a single pass, or you re-create the pipeline from the source, or, if the result genuinely fits in memory, you collect it into an array (const arr = []; for await (const x of pipe) arr.push(x);) and accept the cost. The streaming approach is for when the dataset doesn't fit, so collecting it usually defeats the point.

The other one is debugging. With an array you can console.log the whole thing and see your data. With a lazy pipeline there's nothing to log until you pull a value through, and a console.log inside a generator only fires when that value is actually demanded. The execution order can surprise you the first few times. It clicks, but there's an adjustment period.

And async generators do carry some per-iteration overhead compared to a tight synchronous loop over an array. If your data comfortably fits in memory and you care about raw speed, the array might genuinely be faster. This technique is about not dying on data that doesn't fit, not about winning microbenchmarks on data that does.

The bit underneath

What I find quietly interesting is that the for await...of loop driving this whole thing is doing something generators were partly built to enable. The pause-and-resume machinery that lets a generator give up control and pick back up later is the same machinery that async/await is built on top of. When you await a promise, your function is effectively yielding control and waiting to be resumed, exactly like a generator yielding a value. async/await is, more or less, a generator and a runner that feeds it resolved promises. Once you've written a few generators by hand, a lot of the async behavior you've been taking on faith stops being magic.

I dug into that whole layer, the two-way communication, yield* composition, the async runner that became async/await, in a short book on generators. It's free. If the pipeline pattern here was useful and you want the full mental model under it, grab it:

Get Your Free Copy
Free Ebook Cover Image

The next time Node tells you it's out of memory, before you reach for a bigger heap, ask whether you ever needed all that data at once in the first place. Usually you didn't.

A working demo of the ideas discussed in this post can be found in this GitHub repository:

Verification environment

Reproducible checks for every measurable claim in the article "Processing a 2GB CSV in Node Without Running Out of Memory."

Nothing here is mocked. It generates a real CSV, runs both the naive load-everything approach and the generator pipeline in separate processes measures peak memory, and asserts the totals are correct against an independently computed expected sum.

Requirements

  • Node.js 18 or newer (tested on Node 22). No npm install, zero dependencies.

Quick start

# 1. Run the full check at the article's size (2,000,000 rows / ~45 MB)
node verify.js

# 2. Prove the headline claim: naive dies, pipeline survives the same heap cap
./stress.sh

That's it. verify.js exits 0 if all checks pass. stress.sh exits 0 if the naive approach crashes while the pipeline succeeds.

What each claim maps to

Claim in the article How it's verified File
Both approaches produce the same total Both totals

Cheers :)