Security News
Combatting Alert Fatigue by Prioritizing Malicious Intent
In 2023, data breaches surged 78% from zero-day and supply chain attacks, but developers are still buried under alerts that are unable to prevent these threats.
The memfs npm package is an in-memory filesystem that mimics the Node.js fs module. It allows you to create an ephemeral file system that resides entirely in memory, without touching the actual disk. This can be useful for testing, mocking, and various other scenarios where you don't want to perform I/O operations on the real file system.
Creating and manipulating files
This feature allows you to create, read, and write files in memory as if you were using the native fs module.
const { Volume } = require('memfs');
const vol = new Volume();
vol.writeFileSync('/hello.txt', 'Hello, World!');
const content = vol.readFileSync('/hello.txt', 'utf8');
console.log(content); // Outputs: Hello, World!
Directory operations
This feature enables you to create directories, list their contents, and perform other directory-related operations, all in memory.
const { Volume } = require('memfs');
const vol = new Volume();
vol.mkdirSync('/mydir');
vol.writeFileSync('/mydir/file.txt', 'My file content');
const files = vol.readdirSync('/mydir');
console.log(files); // Outputs: ['file.txt']
Linking and symlinking
This feature allows you to create hard links and symbolic links, mimicking the behavior of links on a real file system.
const { Volume } = require('memfs');
const vol = new Volume();
vol.writeFileSync('/original.txt', 'Content of original');
vol.linkSync('/original.txt', '/link.txt');
vol.symlinkSync('/original.txt', '/symlink.txt');
const linkContent = vol.readFileSync('/link.txt', 'utf8');
const symlinkContent = vol.readlinkSync('/symlink.txt');
console.log(linkContent); // Outputs: Content of original
console.log(symlinkContent); // Outputs: /original.txt
File system watching
This feature provides the ability to watch for changes in the file system, similar to fs.watch in the native fs module.
const { Volume } = require('memfs');
const vol = new Volume();
const fs = vol.promises;
async function watchExample() {
await fs.writeFile('/watched.txt', 'Initial content');
fs.watch('/watched.txt', (eventType, filename) => {
console.log(`Event type: ${eventType}; File: ${filename}`);
});
await fs.writeFile('/watched.txt', 'Updated content');
}
watchExample();
mock-fs is a package that provides a mock file system for Node.js. It is similar to memfs in that it allows you to create an in-memory file system for testing purposes. However, mock-fs overrides the native fs module, while memfs provides a separate file system instance.
unionfs is a package that can combine multiple file systems into a single cohesive file system interface. It can be used with memfs to overlay an in-memory file system on top of the real file system, providing a way to mix real and virtual file system operations.
fs-mock is another in-memory file system module for Node.js. It offers similar functionality to memfs, allowing you to mock the fs module for testing. It differs in API and implementation details, and the choice between fs-mock and memfs may come down to personal preference or specific use-case requirements.
In-memory file-system with Node's fs
API.
fs
API implemented, see API StatusBuffer
sUsage:
import {fs} from 'memfs';
fs.writeFileSync('/hello.txt', 'World!');
fs.readFileSync('/hello.txt', 'utf8'); // World!
Create a file system from a plain JSON:
import {fs, vol} from 'memfs';
vol.importJSON({
'./README.md': '1',
'./src/index.js': '2',
'./node_modules/debug/index.js': '3',
}, '/app');
fs.readFileSync('/app/README.md', 'utf8'); // 1
vol.readFileSync('/app/src/index.js', 'utf8'): // 2
Export to JSON:
vol.writeFileSync('/script.sh', '#! /bin/bash');
vol.toJSON(); // {"/script.sh": "#! /bin/bash"}
Use it for testing:
vol.writeFileSync('/foo', 'bar');
expect(vol.toJSON()).to.eql({"/foo": "bar"});
Other filesystem goodies:
unionfs
- creates a union of multiple filesystem volumeslinkfs
- redirects filesystem pathsfs-monkey
- monkey-patches Node's fs
module and require
functionlibfs
- real filesystem (that executes UNIX system calls) implemented in JavaScriptCreate as many filesystem volumes as you need:
import {Volume} from 'memfs';
const vol = Volume.fromJSON({'/foo': 'bar'});
vol.readFileSync('/foo'); // bar
Use memfs
together with unionfs
to create one filesystem
from your in-memory volumes and the real disk filesystem:
import * as fs from 'fs';
import {ufs} from 'unionfs';
ufs
.use(fs)
.use(vol);
ufs.readFileSync('/foo'); // bar
Use fs-monkey
to monkey-patch Node's require
function:
import {patchRequire} from 'fs-monkey';
vol.writeFileSync('/index.js', 'console.log("hi world")');
patchRequire(vol);
require('/index'); // hi world
This package depends on the following Node modules: buffer
, events
,
streams
, path
.
It also uses process
and setImmediate
globals, but mocks them, if not
available.
vol
vs fs
This package exports vol
and fs
objects which both can be used for
filesystem operations but are slightly different.
import {vol, fs} from 'memfs';
vol
is an instance of Volume
constructor, it is a default volume created
for your convenience. fs
in and fs-like object created from vol
using
createFsFromVolume(vol)
, see reference below.
Volume
Volume
is a constructor function for creating new volumes:
import {Volume} from 'memfs';
const vol = new Volume;
Volume
implements all Node's filesystem methods:
vol.writeFileSync('/foo', 'bar');
But it does not hold constants or constructor functions:
vol.F_OK; // undefined
vol.ReadStream; // undefined
A new volume can be create using the Volume.fromJSON
convenience method:
const vol = Volume.fromJSON({
'/app/index.js': '...',
'/app/package.json': '...',
});
It is just a shorthand for vol.fromJSON
, see below.
Volume
instance vol
vol.fromJSON(json[, cwd])
Adds files from a flat json
object to the volume vol
. The cwd
argument
is optional and is used to compute absolute file paths, if a file path is
given in a relative form.
vol.fromJSON({
'./index.js': '...',
'./package.json': '...',
}, '/app');
vol.mountSync(cwd, json)
Legacy method, which is just an alias for vol.fromJSON
.
vol.toJSON([paths[, json[, isRelative]]])
Exports the whole contents of the volume recursively to a flat JSON object.
paths
is an optional argument that specifies one or more paths to be exported.
If this argument is omitted, the whole volume is exported. paths
can be
an array of paths. A path can be a string, Buffer
or an URL
object.
json
is an optional object parameter where the list of files will be added.
isRelative
is boolean that specifies if returned paths should be relative.
vol.mkdirp(path, callback)
Creates a directory tree recursively. path
is specifies a directory to
create and can be a string, Buffer
, or an URL
object. callback
is
called on completion and may receive only one argument - an Error
object.
vol.mkdirpSync(path)
A synchronous version of vol.mkdirp
. This method throws.
FSWatcher
ReadStream
WriteStream
Stats
access(path[, mode], callback)
accessSync(path[, mode])
appendFile(file, data[, options], callback)
appendFileSync(file, data[, options])
chmod(path, mode, callback)
chmodSync(path, mode)
chown(path, uid, gid, callback)
chownSync(path, uid, gid)
close(fd, callback)
closeSync(fd)
createReadStream(path[, options])
createWriteStream(path[, options])
exists(path, callback)
existsSync(path)
fchmod(fd, mode, callback)
fchmodSync(fd, mode)
fchown(fd, uid, gid, callback)
fchownSync(fd, uid, gid)
fdatasync(fd, callback)
fdatasyncSync(fd)
fstat(fd, callback)
fstatSync(fd)
fsync(fd, callback)
fsyncSync(fd)
ftruncate(fd[, len], callback)
ftruncateSync(fd[, len])
futimes(fd, atime, mtime, callback)
futimesSync(fd, atime, mtime)
lchmod(path, mode, callback)
lchmodSync(path, mode)
lchown(path, uid, gid, callback)
lchownSync(path, uid, gid)
link(existingPath, newPath, callback)
linkSync(existingPath, newPath)
lstat(path, callback)
lstatSync(path)
mkdir(path[, mode], callback)
mkdirSync(path[, mode])
mkdtemp(prefix[, options], callback)
mkdtempSync(prefix[, options])
open(path, flags[, mode], callback)
openSync(path, flags[, mode])
read(fd, buffer, offset, length, position, callback)
readSync(fd, buffer, offset, length, position)
readdir(path[, options], callback)
readdirSync(path[, options])
readFile(path[, options], callback)
readFileSync(path[, options])
readlink(path[, options], callback)
readlinkSync(path[, options])
realpath(path[, options], callback)
realpathSync(path[, options])
rename(oldPath, newPath, callback)
renameSync(oldPath, newPath)
rmdir(path, callback)
rmdirSync(path)
stat(path, callback)
statSync(path)
symlink(target, path[, type], callback)
symlinkSync(target, path[, type])
truncate(path[, len], callback)
truncateSync(path[, len])
unlink(path, callback)
unlinkSync(path)
utimes(path, atime, mtime, callback)
utimesSync(path, atime, mtime)
watch(filename[, options][, listener])
watchFile(filename[, options], listener)
unwatchFile(filename[, listener])
write(fd, buffer[, offset[, length[, position]]], callback)
write(fd, string[, position[, encoding]], callback)
writeFile(file, data[, options], callback)
writeFileSync(file, data[, options])
writeSync(fd, buffer[, offset[, length[, position]]])
writeSync(fd, string[, position[, encoding]])
FAQs
In-memory file-system with Node's fs API.
The npm package memfs receives a total of 12,921,949 weekly downloads. As such, memfs popularity was classified as popular.
We found that memfs demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
In 2023, data breaches surged 78% from zero-day and supply chain attacks, but developers are still buried under alerts that are unable to prevent these threats.
Security News
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.
Security News
License exceptions modify the terms of open source licenses, impacting how software can be used, modified, and distributed. Developers should be aware of the legal implications of these exceptions.