日本語

Node.js ERR_STRING_TOO_LONG: Causes and Fixes

​​Node.js​JavaScript,Troubleshooting,V8

When you read a large file with readFileSync(path, 'utf8') in Node.js, the script can stop with Error: Cannot create a string longer than 0x1fffffe8 characters (the code is ERR_STRING_TOO_LONG). The cause is not a lack of memory. A single string has a maximum length. If you stop turning the whole file into one string and rewrite the code to read it line by line with readline, the error goes away.

This error appears when a Node.js script reads a log or CSV file of several hundred MB to aggregate it. In my test environment, I created a log file of about 625 MB, triggered the error, and confirmed that the message appeared and that the rewritten version finished the aggregation.

Note

The test environment was Ubuntu 24.04 (16 GB of memory) with Node.js 22.23.5 (V8 12.4). I did not test Windows, macOS, Node.js versions other than 22, 32-bit environments, reading one large JSON document, or files larger than 2 GB.

The message when reading a file of about 625 MB with readFileSync

For testing, I created access.log (625,352,000 bytes) with 14 million lines in this form:

text
2026-11-01T00:00:00Z GET /items/0 200 0
2026-11-01T00:00:01Z GET /items/1 200 1
2026-11-01T00:00:02Z GET /items/2 200 2

The following read-all.mjs reads the whole file as one string and counts the lines for each status code in the fourth column.

js
import { readFileSync } from 'node:fs';

const text = readFileSync('access.log', 'utf8');
const counts = {};
for (const line of text.split('\n')) {
  if (!line) continue;
  const status = line.split(' ')[3];
  counts[status] = (counts[status] ?? 0) + 1;
}
console.log(counts);

When I ran node read-all.mjs, it printed the following and exited with code 1. (The path has been replaced with an example value.)

text
node:fs:440
    return binding.readFileUtf8(path, stringToFlags(options.flag));
                   ^

Error: Cannot create a string longer than 0x1fffffe8 characters
    at readFileSync (node:fs:440:20)
    at file:///path/to/app/read-all.mjs:3:14
    at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5) {
  code: 'ERR_STRING_TOO_LONG'
}

Node.js v22.23.5

The script stopped at line 3, the readFileSync call, and never reached split. The failure happens when the file contents are turned into one string. The Node.js error list describes ERR_STRING_TOO_LONG as the error for trying to create a string longer than the allowed length.

0x1fffffe8 is the maximum string length

The 0x1fffffe8 in the message is 536,870,888 in decimal. You can check this value with buffer.constants.MAX_STRING_LENGTH. According to the description of MAX_STRING_LENGTH in the Buffer documentation, this is the maximum length a string can have, and it can differ depending on the JavaScript engine in use.

I ran max-length.mjs, which creates a string of exactly the maximum length and a string one character longer.

js
import { constants } from 'node:buffer';

const max = constants.MAX_STRING_LENGTH;
console.log('MAX_STRING_LENGTH:', max, '(0x' + max.toString(16) + ')');

// A string of exactly the maximum length can be created
console.log('上限ちょうど:', Buffer.alloc(max, 'a').toString('latin1').length);

// Even one character over the limit cannot be created
try {
  Buffer.alloc(max + 1, 'a').toString('latin1');
} catch (err) {
  console.log('上限 + 1:', err.code, err.message);
}
console
$ node max-length.mjs
MAX_STRING_LENGTH: 536870888 (0x1fffffe8)
上限ちょうど: 536870888
上限 + 1: ERR_STRING_TOO_LONG Cannot create a string longer than 0x1fffffe8 characters

A string of exactly the maximum length could be created, and a string one character longer caused the same error. For data where each character is one byte, the boundary in my test environment was about 512 MiB.

Increasing –max-old-space-size does not make it go away

Unlike an out-of-memory error, this error does not go away when you raise the heap limit. I ran node --max-old-space-size=8192 read-all.mjs with the heap limit set to 8 GiB using –max-old-space-size. It printed the same Cannot create a string longer than 0x1fffffe8 characters as before and exited with code 1. The limit applies to the length of a single string, not to the amount of memory available.

Reading the same log with fs/promises readFile or Buffer also fails

I also tried the same access.log with reading methods other than readFileSync. They all try to turn the whole file into one string.

read-promise.mjs reads the file with the Promise-based readFile, passing 'utf8'. Its error message was different.

js
import { readFile } from 'node:fs/promises';

const text = await readFile('access.log', 'utf8');
console.log(text.length);
text
node:internal/fs/promises:591
      result += decoder.write(readBuffer);
                        ^

RangeError: Invalid string length
    at readFileHandle (node:internal/fs/promises:591:25)
    at async file:///path/to/app/read-promise.mjs:3:14

Node.js v22.23.5

The error is RangeError: Invalid string length, and it has no code. The source line shown above the stack (result += decoder.write(readBuffer);) is where the code appends the data it has read to a string called result, and the string exceeds the limit at that point. When code using fs/promises exceeds the limit, you get this message. The cause and the fix are the same.

If you read without specifying an encoding, readFileSync returns a Buffer. Reading into a Buffer succeeded, but the failure came when I converted it to a string with toString() (read-buffer.mjs).

js
import { readFileSync } from 'node:fs';

const buf = readFileSync('access.log');
console.log('Buffer のバイト数:', buf.length);
const text = buf.toString('utf8');
console.log(text.length);
text
Buffer のバイト数: 625352000
node:buffer:640
    slice: (buf, start, end) => buf.utf8Slice(start, end),
                                    ^

Error: Cannot create a string longer than 0x1fffffe8 characters
    at Object.slice (node:buffer:640:37)
    at Buffer.toString (node:buffer:868:14)
    at file:///path/to/app/read-buffer.mjs:5:18
    at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5) {
  code: 'ERR_STRING_TOO_LONG'
}

Node.js v22.23.5

For Japanese text files, the boundary depends on how you read the file

MAX_STRING_LENGTH is a limit measured in characters (the number of UTF-16 code units). For Japanese text, where each character is 3 bytes in UTF-8, the character count is about one third of the byte count. You might expect that a file three times larger could be read. In my test environment, the results depended on how the file was read.

First, multibyte-boundary.mjs converts a Buffer filled with the character U+3042 to a string using toString('utf8'). I ran it with a size 2 bytes below the limit and with a size 1 byte above it.

js
import { constants } from 'node:buffer';

const max = constants.MAX_STRING_LENGTH;
for (const bytes of [max - 2, max + 1]) {
  // A Buffer filled with the 3-byte UTF-8 character U+3042. max - 2 and max + 1 are both divisible by 3
  const buf = Buffer.alloc(bytes, 'あ');
  try {
    const text = buf.toString('utf8');
    console.log(`${bytes} バイト: ${text.length} 文字の文字列になった`);
  } catch (err) {
    console.log(`${bytes} バイト: ${err.code}`);
  }
}
console
$ node multibyte-boundary.mjs
536870886 バイト: 178956962 文字の文字列になった
536870889 バイト: ERR_STRING_TOO_LONG

The Buffer that was 1 byte over the limit would have been about 179 million characters when converted, roughly a third of the limit. Even so, exceeding the byte limit by just 1 byte produced ERR_STRING_TOO_LONG.

Next, I created a file ja.txt with 536,870,889 bytes containing only the character U+3042, and read it with both readFileSync and readFile from fs/promises, passing 'utf8' to both (read-ja.mjs).

js
import { readFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';

try {
  console.log('readFileSync:', readFileSync('ja.txt', 'utf8').length, '文字');
} catch (err) {
  console.log('readFileSync:', err.code);
}
try {
  console.log('readFile(fs/promises):', (await readFile('ja.txt', 'utf8')).length, '文字');
} catch (err) {
  console.log('readFile(fs/promises):', err.name, err.message);
}
console
$ node read-ja.mjs
readFileSync: ERR_STRING_TOO_LONG
readFile(fs/promises): 178956963 文字

readFileSync failed, while readFile from fs/promises returned a string of 178,956,963 characters. In my test environment, readFileSync and toString() failed whenever the byte count exceeded the limit, even when the character count was within it. readFile from fs/promises failed for the log file whose character count exceeded the limit, but it could read the Japanese text file whose byte count exceeded the limit while its character count stayed within it. For files larger than about 512 MiB, you cannot read them with readFileSync, at least, even if the content is Japanese.

Fix it by reading line by line with readline

To fix this, don't turn the whole file into one string. Read it in pieces and process each piece. For a format with one record per line, such as a log or CSV, combining fs.createReadStream() with readline is a simple option. I rewrote read-all.mjs as the following read-lines.mjs, using the same pattern as the readline documentation example for reading a file line by line.

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

const rl = createInterface({
  input: createReadStream('access.log', { encoding: 'utf8' }),
  crlfDelay: Infinity,
});
const counts = {};
for await (const line of rl) {
  if (!line) continue;
  const status = line.split(' ')[3];
  counts[status] = (counts[status] ?? 0) + 1;
}
console.log(counts);

crlfDelay: Infinity makes a \r\n sequence count as one line break, even in files with \r\n line endings. The documentation example also includes this option.

When I ran it on the same access.log, it printed the aggregation results without any error and exited with code 0.

console
$ node read-lines.mjs
{ '200': 7000001, '304': 2333333, '404': 2333333, '500': 2333333 }

The four counts add up to 14,000,000, which matches the number of lines in the file. Only one line at a time is converted to a string, so the size of the whole file is unrelated to the string length limit, as long as no single line is long enough to exceed it.

Point

If file reading produces ERR_STRING_TOO_LONG or RangeError: Invalid string length, check the lines where you pass 'utf8' to readFileSync or readFile, and the lines where you call toString() on a Buffer holding the whole file.

​Posted by 86