Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,8 @@ function tryReadSync(fd, isUserFd, buffer, pos, len) {
function readFileSync(path, options) {
options = getOptions(options, { flag: 'r' });

if (options.encoding === 'utf8' || options.encoding === 'utf-8') {
if (options.encoding === 'utf8' || options.encoding === 'utf-8' ||
options.encoding === 'UTF8' || options.encoding === 'UTF-8') {
if (!isInt32(path)) {
path = getValidatedPath(path);
}
Expand Down Expand Up @@ -2390,7 +2391,8 @@ function writeFileSync(path, data, options) {
const flag = options.flag || 'w';

// C++ fast path for string data and UTF8 encoding
if (typeof data === 'string' && (options.encoding === 'utf8' || options.encoding === 'utf-8')) {
if (typeof data === 'string' && (options.encoding === 'utf8' || options.encoding === 'utf-8' ||
options.encoding === 'UTF8' || options.encoding === 'UTF-8')) {
if (!isInt32(path)) {
path = getValidatedPath(path);
}
Expand Down
49 changes: 49 additions & 0 deletions test/parallel/test-fs-utf8-fast-path-casing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
'use strict';

// This test ensures that fs.readFileSync and fs.writeFileSync
// accept all valid UTF8 encoding variants (utf8, utf-8, UTF8, UTF-8).
// Refs: https://github.com/nodejs/node/issues/49888

const common = require('../common');
const tmpdir = require('../../test/common/tmpdir');
const assert = require('assert');
const fs = require('fs');
const path = require('path');

tmpdir.refresh();

const testContent = 'Hello, World! 你好,世界!';
const encodings = ['utf8', 'utf-8', 'UTF8', 'UTF-8'];

// Test writeFileSync and readFileSync with different UTF8 variants
for (const encoding of encodings) {
const testFile = tmpdir.resolve(`test_utf8_fast_path_${encoding}.txt`);

// Test writeFileSync
fs.writeFileSync(testFile, testContent, { encoding });

// Test readFileSync
const result = fs.readFileSync(testFile, { encoding });
assert.strictEqual(result, testContent,
`readFileSync should return correct content for encoding "${encoding}"`);
}

// Test with file descriptor
for (const encoding of encodings) {
const testFile = tmpdir.resolve(`test_utf8_fast_path_fd_${encoding}.txt`);

// Write with fd
const fdWrite = fs.openSync(testFile, 'w');
fs.writeFileSync(fdWrite, testContent, { encoding });
fs.closeSync(fdWrite);

// Read with fd
const fdRead = fs.openSync(testFile, 'r');
const result = fs.readFileSync(fdRead, { encoding });
fs.closeSync(fdRead);

assert.strictEqual(result, testContent,
`readFileSync with fd should return correct content for encoding "${encoding}"`);
}

console.log('All UTF8 fast path casing tests passed!');