-
Notifications
You must be signed in to change notification settings - Fork 86
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: encoding utf8 strings in node 20
The writeFileUtf8 binding used by node 20 was not correctly encoding strings as utf8, and recording the file length as String.prototype.length, which returns number of utf-16 code units. If you wrote a string containing code points with a different number of utf-8 code units than utf-16 code units, then read the file back the returned string would be truncated by the difference in the number of code units.
- Loading branch information
Caleb ツ Everett
committed
Jan 3, 2025
1 parent
00cc7b5
commit f5e49e0
Showing
2 changed files
with
41 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
const helper = require('../helper.js'); | ||
const assert = helper.assert; | ||
const fs = require('fs'); | ||
const mock = require('../../lib/index.js'); | ||
|
||
const CHARS = [ | ||
// // 1 utf-16, 1 utf-8 byte | ||
'A', | ||
|
||
// 1 utf-16 code unit, 3 utf-8 bytes | ||
'’', | ||
|
||
// // 2 utf-16 code units, 4 utf-8 bytes | ||
'😄', | ||
]; | ||
|
||
const ENCODINGS = ['utf8', 'utf16le', 'latin1']; | ||
|
||
for (const encoding of ENCODINGS) { | ||
for (const char of CHARS) { | ||
describe(`Encoding (${encoding} ${char})`, () => { | ||
const buffer = Buffer.from(char, encoding); | ||
|
||
beforeEach(() => mock()); | ||
afterEach(() => mock.restore()); | ||
|
||
beforeEach(() => fs.writeFileSync('file', char, {encoding})); | ||
|
||
it(`writes ${buffer.length} bytes`, () => { | ||
assert.strictEqual(fs.statSync('file').size, buffer.length); | ||
}); | ||
|
||
it('reads the written value (buffer)', () => { | ||
const out = fs.readFileSync('file'); | ||
assert.sameOrderedMembers(Array.from(out), Array.from(buffer)); | ||
}); | ||
}); | ||
} | ||
} |