@ezdevlol/memfs
Version:
In-memory file-system with Node's fs API.
58 lines (57 loc) • 2.26 kB
JavaScript
import Stats from './Stats';
import Dirent from './Dirent';
import { Volume, toUnixTimestamp, } from './volume';
import { constants } from './constants';
import { fsSynchronousApiList } from './node/lists/fsSynchronousApiList';
import { fsCallbackApiList } from './node/lists/fsCallbackApiList';
const { F_OK, R_OK, W_OK, X_OK } = constants;
export { Volume };
// Default volume.
export const vol = new Volume();
export function createFsFromVolume(vol) {
const fs = { F_OK, R_OK, W_OK, X_OK, constants, Stats, Dirent };
// Bind FS methods.
for (const method of fsSynchronousApiList)
if (typeof vol[method] === 'function')
fs[method] = vol[method].bind(vol);
for (const method of fsCallbackApiList)
if (typeof vol[method] === 'function')
fs[method] = vol[method].bind(vol);
fs.StatWatcher = vol.StatWatcher;
fs.FSWatcher = vol.FSWatcher;
fs.WriteStream = vol.WriteStream;
fs.ReadStream = vol.ReadStream;
fs.promises = vol.promises;
// Handle realpath and realpathSync with their .native properties
if (typeof vol.realpath === 'function') {
fs.realpath = vol.realpath.bind(vol);
if (typeof vol.realpath.native === 'function') {
fs.realpath.native = vol.realpath.native.bind(vol);
}
}
if (typeof vol.realpathSync === 'function') {
fs.realpathSync = vol.realpathSync.bind(vol);
if (typeof vol.realpathSync.native === 'function') {
fs.realpathSync.native = vol.realpathSync.native.bind(vol);
}
}
fs._toUnixTimestamp = toUnixTimestamp;
fs.__vol = vol;
return fs;
}
export const fs = createFsFromVolume(vol);
/**
* Creates a new file system instance.
*
* @param json File system structure expressed as a JSON object.
* Use `null` for empty directories and empty string for empty files.
* @param cwd Current working directory. The JSON structure will be created
* relative to this path.
* @returns A `memfs` file system instance, which is a drop-in replacement for
* the `fs` module.
*/
export const memfs = (json = {}, cwd = '/') => {
const vol = Volume.fromNestedJSON(json, cwd);
const fs = createFsFromVolume(vol);
return { fs, vol };
};