Fix RangeError: Invalid string length when reading large JSON in Node.js
Node.js throws ERR_STRING_TOO_LONG or RangeError: Invalid string length when a JSON file or a JSON.stringify result would be one string longer than V8 allows, about 512 MB. More memory does not fix it. The fix is to stop building the string: parse the file as a stream in code, write records one at a time, and inspect the file from the shell with gronify search, which never loads it.
Updated
Which error you get depends on the call
The examples use export.json, a 582 MB minified array of 2.8 million orders. This is the usual way to load a JSON file in Node.js:
wc -c export.json 582287912 export.jsoncat load.jsconst fs = require("node:fs");const orders = JSON.parse(fs.readFileSync("export.json", "utf8"));console.log(orders.length);node load.jsnode:fs:440 return binding.readFileUtf8(path, stringToFlags(options.flag)); ^Error: Cannot create a string longer than 0x1fffffe8 characters at Object.readFileSync (node:fs:440:20) at Object.<anonymous> (/private/tmp/gg/big/load.js:2:30) at Module._compile (node:internal/modules/cjs/loader:1781:14) at Object..js (node:internal/modules/cjs/loader:1913:10) at Module.load (node:internal/modules/cjs/loader:1505:32) at Function._load (node:internal/modules/cjs/loader:1309:12) at wrapModuleLoad (node:internal/modules/cjs/loader:254:19) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5) at node:internal/main/run_main_module:36:49 { code: 'ERR_STRING_TOO_LONG'}Node.js v22.23.1JSON.parse never ran. readFileSync failed while turning the bytes into one string. The same limit produces a second message when the string is built in JavaScript rather than in Node's C++ code, as fs.promises.readFile does:
node load-async.mjsnode:internal/fs/promises:591 result += decoder.write(readBuffer); ^RangeError: Invalid string length at readFileHandle (node:internal/fs/promises:591:25) at async file:///private/tmp/gg/big/load-async.mjs:2:27Node.js v22.23.1Writing hits the same wall. save.js builds 2.8 million order objects in memory, which fits, and then calls fs.writeFileSync("copy.json", JSON.stringify(orders)). The objects are fine; the single string JSON.stringify returns is too long:
node save.js/private/tmp/gg/big/save.js:6fs.writeFileSync("copy.json", JSON.stringify(orders)); ^RangeError: Invalid string length at JSON.stringify (<anonymous>) at Object.<anonymous> (/private/tmp/gg/big/save.js:6:36) at Module._compile (node:internal/modules/cjs/loader:1781:14) at Object..js (node:internal/modules/cjs/loader:1913:10) at Module.load (node:internal/modules/cjs/loader:1505:32) at Function._load (node:internal/modules/cjs/loader:1309:12) at wrapModuleLoad (node:internal/modules/cjs/loader:254:19) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5) at node:internal/main/run_main_module:36:49Node.js v22.23.1| Call | Error | Fix |
|---|---|---|
fs.readFileSync(path, "utf8") | ERR_STRING_TOO_LONG | Stream the file into a parser |
JSON.parse(fs.readFileSync(path)) with a Buffer | ERR_STRING_TOO_LONG, from Buffer.toString | Stream the file into a parser |
require("./export.json") | ERR_STRING_TOO_LONG | Stream the file into a parser |
fs.promises.readFile(path, "utf8") | RangeError: Invalid string length | Stream the file into a parser |
data += chunk in a stream data handler | RangeError: Invalid string length | Parse the chunks instead of joining them |
JSON.stringify(records) | RangeError: Invalid string length | Write one record at a time |
Why more memory does not help
Both messages report one limit: the longest string V8 will create, which Node exposes as buffer.constants.MAX_STRING_LENGTH. 0x1fffffe8 in the first message is the same number in hexadecimal.
node -p 'require("buffer").constants.MAX_STRING_LENGTH'536870888That is 2^29 minus 24 UTF-16 code units. In ASCII JSON one byte is one code unit, so the ceiling is a file of about 512 MB. It is a constant of the engine, not of the heap, so --max-old-space-size changes nothing; searching large JSON files shows the same error with a 16 GB heap and covers the separate 2 GiB read limit above it.
Fix it in code: parse the file as a stream
A streaming parser reads the file in chunks and hands your code one array element at a time, so no step holds the whole file. stream-json is one such parser; @streamparser/json is another. This script counts refunded orders in the file JSON.parse could not read:
cat sum-refunds.mjsimport fs from "node:fs";import chain from "stream-chain";import { parser } from "stream-json";import { streamArray } from "stream-json/streamers/stream-array.js";let refunded = 0;const orders = chain([ fs.createReadStream(process.argv[2]), parser(), streamArray(),]);orders.on("data", ({ value }) => { if (value.status === "refunded") refunded += 1;});orders.on("end", () => console.log(refunded));/usr/bin/time -l node sum-refunds.mjs export.json 2>&1 | grep -E '^[0-9]+$|real|maximum resident'560000 16.08 real 15.29 user 0.71 sys 113934336 maximum resident set sizePeak memory was 109 MiB for a 582 MB file. streamArray() fits a top-level array. For records nested under a key, such as {"orders": [...]}, add stream-json's pick filter in front of it to select that array.
Fix JSON.stringify: write one record at a time
To write a large array, stringify each record on its own and write the pieces to a file stream. Waiting for drain when write returns false keeps memory flat:
cat write-array.mjsimport fs from "node:fs";import { once } from "node:events";async function writeJsonArray(path, records) { const out = fs.createWriteStream(path); let first = true; for (const record of records) { const text = (first ? "[" : ",") + JSON.stringify(record); first = false; if (!out.write(text)) await once(out, "drain"); } out.end(first ? "[]\n" : "]\n"); await once(out, "finish");}function* orders(count) { for (let i = 0; i < count; i++) { yield { id: "ord_" + String(i).padStart(8, "0"), status: "paid" }; }}await writeJsonArray(process.argv[2], orders(Number(process.argv[3])));node write-array.mjs copy.json 20000000wc -c copy.json 760000002 copy.jsongronify search copy.json --count ord_20000000The 760 MB result is valid JSON: Gronify parsed it to the end and counted all 20 million records. If whoever reads the file can take it, write JSON Lines instead, one object per line, so each line is a small string on the reading side too.
Inspect the file without writing code
Often the error appears while you only want to look inside the file: check its shape, count something, or pull out one record. Gronify is a Node.js CLI, but it tokenizes the raw bytes in chunks and writes each json.path = value line as it goes, so it never creates the long string. Install Gronify, then:
gronify flatten --limit 15 export.jsonjson = []json[0] = {}json[0].id = "ord_00000000"json[0].created = "2026-10-01T00:00:00.000Z"json[0].status = "paid"json[0].amount = {}json[0].amount.value = 0json[0].amount.currency = "EUR"json[0].customer = {}json[0].customer.id = "cus_0"json[0].customer.country = "DE"json[0].items = []json[0].items[0] = {}json[0].items[0].sku = "SKU-0"json[0].items[0].qty = 1Stopped after 15 lines (--limit); there may be moregronify search export.json --count 'status = "refunded"'560000gronify search export.json --count card_declined280000flatten --limit 15 printed the first record and stopped reading. The counts read the whole file. Including = and the quotes in the first term pins it to the status value, so a refund note in another field would not be counted.
Find one record and get it back as JSON
-m 1 finds the record's array index and stops reading. A regex on that index then selects every line of the record, sed renames the record's path to the root, and gronify unflatten turns the lines back into JSON:
gronify search export.json -m 1 ord_01234567json[1234567].id = "ord_01234567"Stopped after 1 match (--max-count); there may be moregronify search export.json --regex '^json\[1234567\]' | sed 's/^json\[1234567\]/json/' | gronify --pretty unflatten{ "id": "ord_01234567", "created": "2026-10-15T06:56:07.000Z", "status": "paid", "amount": { "value": 289.79, "currency": "EUR" }, "customer": { "id": "cus_136073", "country": "US" }, "items": [ { "sku": "SKU-667", "qty": 2 } ]}The \] in the pattern matters: without it, ^json\[1234567 would also match records 12345670 to 12345679 in a larger file.
Memory
/usr/bin/time -l gronify search export.json --count 'status = "refunded"' 2>&1 | grep -E '^[0-9]+$|real|maximum resident'560000 2.22 real 2.19 user 0.05 sys 55787520 maximum resident set sizePeak memory was 53 MiB, and it does not grow with the number of records. For more on searching files this size, including gzip input and jq --stream, see search a multi-gigabyte JSON file.
Which fix to use
- Your program needs every record: stream the file into a parser such as stream-json.
- Your program writes the file: write one record at a time, or write JSON Lines.
- You need to look inside the file, count values, or pull out a record:
gronify searchandgronify flatten --limit, with no code. - You need to filter or reshape records from the shell:
jq --stream, as shown in the jq alternative guide and searching large JSON files.