In-Memory Filesystem (memory-fs)
memory-fs provides a simple, synchronous and asynchronous, in-memory filesystem abstraction, designed to hold data entirely within a JavaScript object. It mirrors a subset of the Node.js `fs` module API, making it suitable for scenarios where persistent disk I/O is undesirable or impractical, such as build tools, bundlers, and testing environments. The current stable version, 0.5.0, was released in 2017. While not actively developing new features, it is a critical, stable dependency for projects like Webpack, which relies on it for fast, transient asset compilation. Its primary differentiator is its complete in-memory operation and direct API compatibility with many standard `fs` methods, offering a performant alternative to disk-based operations for temporary file storage.
Common errors
-
TypeError: MemoryFileSystem is not a constructor
cause Attempting to call `new` on the result of `require('memory-fs')` when the variable was incorrectly reassigned or handled.fixEnsure `const MemoryFileSystem = require('memory-fs');` directly assigns the constructor to `MemoryFileSystem` and then `const fs = new MemoryFileSystem();` is called. -
ReferenceError: require is not defined in ES module scope
cause Trying to use `require` in a file or project configured for ES modules (`"type": "module"` in package.json).fixThis package is CommonJS-only. For projects using ES modules, you might need to use a bundler (like Webpack) that handles CommonJS dependencies, or restructure your code to load this module in a CommonJS context. -
TypeError: fs.someMethod is not a function
cause Attempting to call an `fs` module method that is not implemented by `memory-fs` (e.g., `fs.watch`, `fs.createReadStream`).fixVerify that the specific `fs` method you need is supported by `memory-fs`. If not, you may need to reconsider its use for that particular operation or find an alternative library.
Warnings
- breaking The `engines` field in package.json restricts compatible Node.js versions. Specifically, it requires Node.js `>=4.3.0 <5.0.0 || >=5.10`. Using unsupported Node.js versions may lead to unexpected behavior or installation failures.
- gotcha memory-fs provides only a subset of the standard Node.js `fs` module API. While it implements common methods like `readFile`, `writeFile`, `readdir`, and `stat`, many advanced or less frequently used `fs` methods are not available.
- gotcha This package is CommonJS-only and does not natively support ES module `import` syntax. Attempting to use `import` will result in a runtime error.
- gotcha Unlike the native `fs` module, `memory-fs` requires explicit instantiation via `new MemoryFileSystem()`. Importing the package directly does not yield a functional filesystem object.
Install
-
npm install memory-fs -
yarn add memory-fs -
pnpm add memory-fs
Imports
- MemoryFileSystem
import MemoryFileSystem from 'memory-fs';
const MemoryFileSystem = require('memory-fs'); - fsInstance
const fs = require('memory-fs'); // Does not return an instanceconst fs = new MemoryFileSystem();
Quickstart
const MemoryFileSystem = require('memory-fs');
const fs = new MemoryFileSystem(); // Optionally pass an initial JavaScript object, e.g., { 'src': { 'main.js': 'console.log("Hello");' } }
// Create directories
fs.mkdirpSync("/a/test/dir");
console.log('Created /a/test/dir');
// Write and read a file
const filePath = "/a/test/dir/file.txt";
fs.writeFileSync(filePath, "Hello World from memory-fs");
console.log(`Content of ${filePath}: ${fs.readFileSync(filePath, 'utf8')}`);
// Async file unlink
fs.unlink(filePath, function(err) {
if (err) {
console.error(`Error unlinking file: ${err.message}`);
return;
}
console.log(`${filePath} unlinked successfully.`);
});
// List directory contents
console.log(`Contents of /a/test: ${fs.readdirSync("/a/test")}`);
// Get file/directory stats
const stats = fs.statSync("/a/test/dir");
console.log(`/a/test/dir is a directory: ${stats.isDirectory()}`);
// Clean up directory
fs.rmdirSync("/a/test/dir");
console.log('Removed /a/test/dir');