Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Node.js, PHP and APIs

JSON.stringify on a huge object throws RangeError: Invalid string length

Your error

RangeError: Invalid string length2 more lines it can show

Fix it fast

Most common cause, 1 of 3

One JSON.stringify call covers the whole dataset

Write the array piece by piece: an async generator yields the opening bracket, each element as its own small JSON string and the closing bracket, and pipeline() streams them into the file or the HTTP response.

Fix
import { pipeline } from 'node:stream/promises';
import { createWriteStream } from 'node:fs';

await pipeline(
  async function* () {
    yield '[';
    for (let i = 0; i < rows.length; i++) {
      yield (i ? ',' : '') + JSON.stringify(rows[i]);
    }
    yield ']';
  },
  createWriteStream('export.json'),
);
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

RangeError: Invalid string length from JSON.stringify means the JSON text would be longer than the V8 single-string cap of 2^29 - 24 UTF-16 code units, about 536 million characters, in Node.js 22 to 26. Serialise one element at a time and stream it with pipeline(), stop building output with +=, and store huge exports as NDJSON read back line by line.

  • Applies to Node.js 22, Node.js 24, Node.js 26
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

Compare the engine's string limit with an estimate of your output. Serialise a sample of the data, scale it up to the full count, and you know whether a single string can ever hold the result.

Run this first
const { constants } = require('node:buffer');
const sample = JSON.stringify(rows.slice(0, 1000)).length;
console.log('limit:', constants.MAX_STRING_LENGTH);
console.log('estimate:', Math.round((sample / 1000) * rows.length));

Then find the line you see in this list and open its fix:

  1. 1One JSON.stringify call covers the whole datasetThe stack points at a single JSON.stringify(data) on an array with millions of entries or on a large nested object
  2. 2The output is collected with += in a loopThe error is thrown at a line like out += line inside a loop that builds a report, CSV or log text
  3. 3The big file is read back into a single stringWriting now works, but readFileSync(file, 'utf8') or buffer.toString() fails with ERR_STRING_TOO_LONG

What does the error look like?

  • RangeError: Invalid string length
  • The error appears only for the largest exports, while smaller ones work
  • code: 'ERR_STRING_TOO_LONG' when the big file is read back

Cause 1 of 3

One JSON.stringify call covers the whole dataset

You seeThe stack points at a single JSON.stringify(data) on an array with millions of entries or on a large nested object

Check

RangeError: Invalid string length is thrown here because one JSON.stringify call has to return the whole dataset as a single string. That string can never be longer than the fixed engine limit. MDN lists the V8 limit as 2^29 - 24 on 64-bit systems.

Check
grep -rn "JSON.stringify(" src/

Fix

Write the array piece by piece: an async generator yields the opening bracket, each element as its own small JSON string and the closing bracket, and pipeline() streams them into the file or the HTTP response.

Fix
import { pipeline } from 'node:stream/promises';
import { createWriteStream } from 'node:fs';

await pipeline(
  async function* () {
    yield '[';
    for (let i = 0; i < rows.length; i++) {
      yield (i ? ',' : '') + JSON.stringify(rows[i]);
    }
    yield ']';
  },
  createWriteStream('export.json'),
);

Verify

Look at both ends of the file: it should open with [ and close with ], with no error printed during the export.

Verify
head -c 120 export.json; echo; tail -c 120 export.json

Confirmed by developer.mozilla.org

Did this fix it?

Cause 2 of 3

The output is collected with += in a loop

You seeThe error is thrown at a line like out += line inside a loop that builds a report, CSV or log text

Check

RangeError: Invalid string length also comes from += in a loop: the variable you append to is a single string, and it crosses the limit at some row even though each row is small. Look for report, CSV or log builders that collect everything before writing.

Check
grep -rnE "\+= *(JSON\.stringify|line|row|chunk)" src/

Fix

Send each piece to a write stream as soon as it is made, and pause on drain when write() returns false, so memory stays flat and no string grows.

Fix
import { createWriteStream } from 'node:fs';
import { once } from 'node:events';

const out = createWriteStream('report.csv');
for (const row of rows) {
  if (!out.write(toCsvLine(row) + '\n')) await once(out, 'drain');
}
out.end();
await once(out, 'finish');

Verify

The job completes for the biggest dataset, and the line count matches the number of rows.

Verify
wc -l report.csv

Confirmed by nodejs.org

Did this fix it?

Cause 3 of 3

The big file is read back into a single string

You seeWriting now works, but readFileSync(file, 'utf8') or buffer.toString() fails with ERR_STRING_TOO_LONG

Check

ERR_STRING_TOO_LONG while reading means the big file is being decoded into one string, which runs into the same cap. Node.js documents that the length of a decoded string is limited by buffer.constants.MAX_STRING_LENGTH. A JSON file whose text runs past about 536 million characters cannot be loaded whole and passed to JSON.parse.

Check
ls -lh export.json

Fix

Store large exports as NDJSON, one JSON value per line, and read them with readline, parsing one line at a time.

Fix
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';

const rl = createInterface({ input: createReadStream('export.ndjson'), crlfDelay: Infinity });
for await (const line of rl) {
  if (line) handle(JSON.parse(line));
}

Verify

The reader finishes and the number of handled records equals the line count of the file.

Verify
wc -l export.ndjson

Confirmed by nodejs.org

Did this fix it?

How do I stop it coming back?

  • Pick a streamable format (a streamed JSON array or NDJSON) for any export that can grow without bound.
  • Skip the space argument of JSON.stringify for large output; indentation adds characters on every nested level.
  • Page through database results with a cursor instead of loading every row before you serialise.
  • Add a test that exports more rows than production has today, so the limit shows up before customers hit it.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: TaxiDex, Workforce.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.