node/test/parallel/test-vfs-destructuring.js
Matteo Collina 569369f927
vfs: dispatch fs/promises to mounted VFS instances
Add mount/unmount lifecycle on `VirtualFileSystem`, a handler registry
that fs.js and fs/promises.js consult via `vfsState.handlers`, and a
router that maps absolute paths to the VFS that owns them. When a VFS
is mounted, the public `fs.*` and `fs/promises` APIs (including
streams, `fs.watch`, and `opendir`) dispatch to the provider for paths
under the mount point, and fall through to the real filesystem
otherwise. Includes per-method dispatch tests, error-path coverage,
multi-mount routing tests, and router unit tests.

Ref: https://github.com/nodejs/node/pull/63115

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/63537
Refs: https://github.com/nodejs/node/pull/63115
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
2026-05-29 17:57:34 +00:00

77 lines
1.9 KiB
JavaScript

// Flags: --experimental-vfs
'use strict';
const common = require('../common');
const assert = require('assert');
const path = require('path');
const vfs = require('node:vfs');
// Destructure fs methods BEFORE mounting any VFS. Because the guards are
// inside each fs method body (not done via monkey-patching), these captured
// references must still route through VFS once a mount is created.
const {
readFileSync,
existsSync,
statSync,
lstatSync,
readdirSync,
realpathSync,
} = require('fs');
// path.resolve here so the mount point and the assertion targets are in the
// platform's native form (e.g. 'D:\vfs_destr' on Windows). VirtualFileSystem
// stores the mount point via path.resolve internally, so we mirror that.
const MOUNT = path.resolve('/vfs_destr');
const FILE = path.join(MOUNT, 'file.txt');
const myVfs = vfs.create();
myVfs.mkdirSync('/sub', { recursive: true });
myVfs.writeFileSync('/file.txt', 'hello from vfs');
myVfs.writeFileSync('/sub/nested.txt', 'nested content');
myVfs.mount(MOUNT);
{
const content = readFileSync(FILE, 'utf8');
assert.strictEqual(content, 'hello from vfs');
}
{
assert.strictEqual(existsSync(FILE), true);
assert.strictEqual(existsSync(path.join(MOUNT, 'nonexistent')), false);
}
{
const stats = statSync(FILE);
assert.strictEqual(stats.isFile(), true);
assert.strictEqual(stats.isDirectory(), false);
}
{
const stats = lstatSync(FILE);
assert.strictEqual(stats.isFile(), true);
}
{
const entries = readdirSync(MOUNT);
assert.ok(entries.includes('file.txt'));
assert.ok(entries.includes('sub'));
}
{
const real = realpathSync(FILE);
assert.strictEqual(real, FILE);
}
const { readdir, lstat } = require('fs/promises');
async function testPromises() {
const entries = await readdir(MOUNT);
assert.ok(entries.includes('file.txt'));
const stats = await lstat(FILE);
assert.strictEqual(stats.isFile(), true);
}
testPromises().then(common.mustCall(() => {
myVfs.unmount();
}));