Files
node/test/parallel/test-vfs-fs-readFileSync.js
T
Trivikram Kamat 8cb83126b8 vfs: read RealFSProvider files from open fd
Read RealFileHandle contents through the open file descriptor instead
of reopening the original real path. This keeps already-open VFS file
descriptors usable after the backing file is renamed.

Use positioned reads so readFileSync() and readFile() preserve the
handle's current offset.

Signed-off-by: Kamat, Trivikram <16024985+trivikr@users.noreply.github.com>
Assisted-by: openai:gpt-5.5
PR-URL: https://github.com/nodejs/node/pull/64104
Fixes: https://github.com/nodejs/node/issues/64103
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-06-27 06:07:44 +00:00

75 lines
2.3 KiB
JavaScript

// Flags: --experimental-vfs
'use strict';
// fs.readFileSync dispatches to VFS for both string paths and VFS-owned fds.
require('../common');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-readFileSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
// Default (buffer) result
{
const buf = fs.readFileSync(path.join(mountPoint, 'src/hello.txt'));
assert.ok(Buffer.isBuffer(buf));
assert.strictEqual(buf.toString(), 'hello world');
}
// utf8 encoding -> string result
assert.strictEqual(
fs.readFileSync(path.join(mountPoint, 'src/hello.txt'), 'utf8'),
'hello world',
);
// Encoding via options object
assert.strictEqual(
fs.readFileSync(path.join(mountPoint, 'src/hello.txt'),
{ encoding: 'utf8' }),
'hello world',
);
// readFileSync via a VFS fd
{
const fd = fs.openSync(path.join(mountPoint, 'src/hello.txt'), 'r');
assert.strictEqual(fs.readFileSync(fd, 'utf8'), 'hello world');
fs.closeSync(fd);
}
myVfs.unmount();
// readFileSync via a RealFSProvider fd remains usable after the backing path
// is renamed.
{
const root = path.join('/tmp', 'vfs-real-readFileSync-' + process.pid);
const realMountPoint = path.join('/tmp', 'vfs-real-readFileSync-mount-' + process.pid);
fs.rmSync(root, { recursive: true, force: true });
fs.rmSync(realMountPoint, { recursive: true, force: true });
fs.mkdirSync(root, { recursive: true });
fs.mkdirSync(realMountPoint, { recursive: true });
const realVfs = vfs
.create(new vfs.RealFSProvider(root), { emitExperimentalWarning: false })
.mount(realMountPoint);
try {
fs.writeFileSync(path.join(root, 'a.txt'), 'still readable');
const fd = fs.openSync(path.join(realMountPoint, 'a.txt'), 'r');
try {
fs.renameSync(path.join(root, 'a.txt'), path.join(root, 'b.txt'));
assert.strictEqual(fs.readFileSync(fd, 'utf8'), 'still readable');
} finally {
fs.closeSync(fd);
}
} finally {
realVfs.unmount();
fs.rmSync(root, { recursive: true, force: true });
fs.rmSync(realMountPoint, { recursive: true, force: true });
}
}