Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
'use strict';
// eslint-disable-next-line no-console
console.log('Using a memfs filesystem...');
const memfs = require('memfs');
const vol = new memfs.Volume();
const fs = memfs.createFsFromVolume(vol);
module.exports = fs;
module.exports.volume = vol;
fromJSON(fsJson: any) {
this.volume = Volume.fromJSON(fsJson);
// @ts-ignore
this.volume.releasedFds = [0, 1, 2];
const fdErr = this.volume.openSync("/dev/stderr", "w");
const fdOut = this.volume.openSync("/dev/stdout", "w");
const fdIn = this.volume.openSync("/dev/stdin", "r");
assert(fdErr === 2, `invalid handle for stderr: ${fdErr}`);
assert(fdOut === 1, `invalid handle for stdout: ${fdOut}`);
assert(fdIn === 0, `invalid handle for stdin: ${fdIn}`);
console.log(fsJson);
this.fs = createFsFromVolume(this.volume);
}
private createFs( volume: Volume ): { [ key: string ]: any } {
// Create filesystem for volume
const volumeFs: { [ key: string ]: any } = createFsFromVolume( volume );
// Now, simply map all (original NodeJS) fs calls to in-memory (memfs) fs calls
const fsFunctionMapping = Object
.keys( fs )
.reduce( ( fsFunctionMapping: { [ key: string ]: any }, functionName: any ): { [ key: string ]: any } => {
fsFunctionMapping[ functionName ] = volumeFs[ functionName ];
return fsFunctionMapping;
}, {
'@global': true // Monkey-patch deeply nested imports as well, affecting the whole dependency tree
} );
// Then, override parts of the mapping for special cases; for now this only includes the ability to access the real filesystem when
// going into the 'node_modules' folder
const fsFunctionMappingWithExceptions = { ...fsFunctionMapping, ...{
existsSync: ( path: string ): boolean => {
return ( path.indexOf( 'node_modules' ) === -1 )
fromJSON(fsJson: any) {
this.volume = new Volume();
this.fromJSONFixed(this.volume, fsJson);
// @ts-ignore
this.fs = createFsFromVolume(this.volume);
this.volume.releasedFds = [0, 1, 2];
const fdErr = this.volume.openSync("/dev/stderr", "w");
const fdOut = this.volume.openSync("/dev/stdout", "w");
const fdIn = this.volume.openSync("/dev/stdin", "r");
assert(fdErr === 2, `invalid handle for stderr: ${fdErr}`);
assert(fdOut === 1, `invalid handle for stdout: ${fdOut}`);
assert(fdIn === 0, `invalid handle for stdin: ${fdIn}`);
}
private init() {
this.volume = new Volume()
this.fs = createFsFromVolume(this.volume)
this.reset()
}
}
import { Volume, createFsFromVolume } from "memfs";
import { patchFs } from "fs-monkey";
export const vol = Volume.fromJSON({});
export const fs = createFsFromVolume(vol);
export function withGlobalFS(thunk: () => T): T {
const unpatch = patchFs(vol);
const ret = thunk();
unpatch();
return ret;
}