buffer: normalize lone "\r" in Blob native line endings

`new Blob(parts, { endings: 'native' })` failed to normalize a
standalone carriage return. The replacement regex only matched
`\n` and `\r\n`, so a lone `\r` (and runs such as `\r\r`) were
left untouched instead of being converted to the platform's
native line ending.

The WHATWG "convert line endings to native" algorithm requires
`\r`, `\n`, and `\r\n` to all be normalized. Match `\r\n` before
a lone `\r` so that CRLF collapses to a single native ending.

Refs: https://w3c.github.io/FileAPI/#convert-line-endings-to-native

Signed-off-by: Daijiro Wachi <daijiro.wachi@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/64115
Refs: https://w3c.github.io/FileAPI/#convert-line-endings-to-native
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Jason Zhang <xzha4350@gmail.com>
This commit is contained in:
Daijiro Wachi authored and RafaelGSS committed 2026-07-29 10:31:28 -03:00
1 parent 5bdbd256e9
commit 0a46d1ef66
2 files changed
+19 -1

No files matched your search

+1 -1
View File
@@ -122,7 +122,7 @@ function getSource(source, endings) {
source = new Uint8Array(source);
} else if (!isArrayBufferView(source)) {
if (endings === 'native')
source = RegExpPrototypeSymbolReplace(/\n|\r\n/g, source, EOL);
source = RegExpPrototypeSymbolReplace(/\r\n|\r|\n/g, source, EOL);
source = enc.encode(source);
}
+18
View File
@@ -407,6 +407,24 @@ assert.throws(() => new Blob({}), {
const b = new Blob(['hello\n'], { endings: 'native' });
assert.strictEqual(b.size, EOL.length + 5);
// The WHATWG "convert line endings to native" algorithm normalizes every
// standalone "\r", "\n", and "\r\n" sequence to the native line ending.
// Refs: https://w3c.github.io/FileAPI/#convert-line-endings-to-native
(async () => {
const cases = [
['a\rb', `a${EOL}b`],
['a\nb', `a${EOL}b`],
['a\r\nb', `a${EOL}b`],
['a\r\rb', `a${EOL}${EOL}b`],
['a\n\rb', `a${EOL}${EOL}b`],
['\r\n\r', `${EOL}${EOL}`],
];
for (const [input, expected] of cases) {
const blob = new Blob([input], { endings: 'native' });
assert.strictEqual(await blob.text(), expected);
}
})().then(common.mustCall());
[1, {}, 'foo'].forEach((endings) => {
assert.throws(() => new Blob([], { endings }), {
code: 'ERR_INVALID_ARG_VALUE',