0
# memory-fs
1
2
A simple in-memory filesystem that stores file and directory data in JavaScript objects. It provides a familiar Node.js fs-like API with both synchronous and asynchronous methods for common filesystem operations. Designed for scenarios where temporary file storage is needed without touching the actual filesystem.
3
4
## Package Information
5
6
- **Package Name**: memory-fs
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install memory-fs`
10
11
## Core Imports
12
13
```javascript
14
const MemoryFileSystem = require("memory-fs");
15
```
16
17
## Basic Usage
18
19
```javascript
20
const MemoryFileSystem = require("memory-fs");
21
22
// Create filesystem instance
23
const fs = new MemoryFileSystem(); // Optionally pass existing data object
24
25
// Create directories
26
fs.mkdirpSync("/a/test/dir");
27
28
// Write files
29
fs.writeFileSync("/a/test/dir/file.txt", "Hello World");
30
31
// Read files
32
const content = fs.readFileSync("/a/test/dir/file.txt"); // Returns Buffer
33
const text = fs.readFileSync("/a/test/dir/file.txt", "utf-8"); // Returns string
34
35
// List directory contents
36
fs.readdirSync("/a/test"); // Returns ["dir"]
37
38
// Check file/directory stats
39
fs.statSync("/a/test/dir").isDirectory(); // Returns true
40
41
// Remove files and directories
42
fs.unlinkSync("/a/test/dir/file.txt");
43
fs.rmdirSync("/a/test/dir");
44
45
// Cross-platform path support
46
fs.mkdirpSync("C:\\\\use\\\\windows\\\\style\\\\paths");
47
```
48
49
## Capabilities
50
51
### Constructor and Initialization
52
53
Create a new in-memory filesystem instance.
54
55
```javascript { .api }
56
/**
57
* Create a new MemoryFileSystem instance
58
* @param {Object} [data] - Optional initial data object to populate filesystem
59
*/
60
class MemoryFileSystem {
61
constructor(data);
62
}
63
```
64
65
### File Existence and Information
66
67
Check if files or directories exist and get their metadata.
68
69
```javascript { .api }
70
/**
71
* Get internal metadata for a file or directory (synchronous)
72
* @param {string} path - File or directory path
73
* @returns {Object|undefined} Internal metadata object or undefined if not found
74
*/
75
meta(path);
76
77
/**
78
* Check if a file or directory exists (synchronous)
79
* @param {string} path - File or directory path
80
* @returns {boolean} True if exists, false otherwise
81
*/
82
existsSync(path);
83
84
/**
85
* Check if a file or directory exists (asynchronous)
86
* @param {string} path - File or directory path
87
* @param {function} callback - Callback function receiving (exists)
88
*/
89
exists(path, callback);
90
91
/**
92
* Get file or directory statistics (synchronous)
93
* @param {string} path - File or directory path
94
* @returns {Object} Stat object with isFile(), isDirectory(), etc. methods
95
*/
96
statSync(path);
97
98
/**
99
* Get file or directory statistics (asynchronous)
100
* @param {string} path - File or directory path
101
* @param {function} callback - Callback function receiving (err, stats)
102
*/
103
stat(path, callback);
104
```
105
106
### File Operations
107
108
Read and write file contents with various encoding options.
109
110
```javascript { .api }
111
/**
112
* Read file contents (synchronous)
113
* @param {string} path - File path
114
* @param {string|Object} [optionsOrEncoding] - Encoding string or options object
115
* @returns {Buffer|string} File contents as Buffer or string if encoding specified
116
*/
117
readFileSync(path, optionsOrEncoding);
118
119
/**
120
* Read file contents (asynchronous)
121
* @param {string} path - File path
122
* @param {string|Object} [encoding] - Encoding string or options object
123
* @param {function} callback - Callback function receiving (err, data)
124
*/
125
readFile(path, encoding, callback);
126
127
/**
128
* Write file contents (synchronous)
129
* @param {string} path - File path
130
* @param {string|Buffer} content - Content to write
131
* @param {string|Object} [optionsOrEncoding] - Encoding string or options object
132
*/
133
writeFileSync(path, content, optionsOrEncoding);
134
135
/**
136
* Write file contents (asynchronous)
137
* @param {string} path - File path
138
* @param {string|Buffer} content - Content to write
139
* @param {string|Object} [encoding] - Optional encoding string or options object
140
* @param {function} callback - Callback function receiving (err)
141
*/
142
writeFile(path, content, [encoding], callback);
143
144
/**
145
* Remove a file (synchronous)
146
* @param {string} path - File path
147
*/
148
unlinkSync(path);
149
150
/**
151
* Remove a file (asynchronous)
152
* @param {string} path - File path
153
* @param {function} callback - Callback function receiving (err)
154
*/
155
unlink(path, callback);
156
```
157
158
### Directory Operations
159
160
Create, read, and remove directories with full cross-platform path support.
161
162
```javascript { .api }
163
/**
164
* Read directory contents (synchronous)
165
* @param {string} path - Directory path
166
* @returns {string[]} Array of file and directory names
167
*/
168
readdirSync(path);
169
170
/**
171
* Read directory contents (asynchronous)
172
* @param {string} path - Directory path
173
* @param {function} callback - Callback function receiving (err, files)
174
*/
175
readdir(path, callback);
176
177
/**
178
* Create a single directory (synchronous)
179
* @param {string} path - Directory path
180
* @throws {Error} If parent directory doesn't exist
181
*/
182
mkdirSync(path);
183
184
/**
185
* Create a single directory (asynchronous)
186
* @param {string} path - Directory path
187
* @param {Object} [options] - Optional options object
188
* @param {function} callback - Callback function receiving (err)
189
*/
190
mkdir(path, [options], callback);
191
192
/**
193
* Create directory recursively (synchronous)
194
* @param {string} path - Directory path
195
*/
196
mkdirpSync(path);
197
198
/**
199
* Create directory recursively (asynchronous)
200
* @param {string} path - Directory path
201
* @param {function} callback - Callback function receiving (err)
202
*/
203
mkdirp(path, callback);
204
205
/**
206
* Remove an empty directory (synchronous)
207
* @param {string} path - Directory path
208
*/
209
rmdirSync(path);
210
211
/**
212
* Remove an empty directory (asynchronous)
213
* @param {string} path - Directory path
214
* @param {function} callback - Callback function receiving (err)
215
*/
216
rmdir(path, callback);
217
```
218
219
### Stream Operations
220
221
Create readable and writable streams for file operations.
222
223
```javascript { .api }
224
/**
225
* Create a readable stream for a file
226
* @param {string} path - File path
227
* @param {Object} [options] - Stream options with start/end properties
228
* @returns {ReadableStream} Readable stream for the file
229
*/
230
createReadStream(path, options);
231
232
/**
233
* Create a writable stream for a file
234
* @param {string} path - File path
235
* @returns {WritableStream} Writable stream for the file
236
*/
237
createWriteStream(path);
238
```
239
240
### Instance Properties
241
242
Path manipulation utilities available as instance properties.
243
244
```javascript { .api }
245
/**
246
* Join path components with proper separator handling
247
* @param {string} path - Base path
248
* @param {string} request - Path component to join
249
* @returns {string} Joined and normalized path
250
*/
251
fs.join(path, request);
252
253
/**
254
* Normalize path by resolving . and .. components
255
* @param {string} path - Path to normalize
256
* @returns {string} Normalized path
257
*/
258
fs.normalize(path);
259
260
/**
261
* Convert path string to array of components
262
* @param {string} path - Path to convert
263
* @returns {string[]} Array of path components
264
*/
265
fs.pathToArray(path);
266
```
267
268
### Symbolic Link Operations
269
270
Limited symbolic link support (readlink throws ENOSYS).
271
272
```javascript { .api }
273
/**
274
* Read symbolic link target (synchronous) - NOT IMPLEMENTED
275
* @param {string} path - Symbolic link path
276
* @throws {Error} Always throws ENOSYS error (not implemented)
277
*/
278
readlinkSync(path);
279
280
/**
281
* Read symbolic link target (asynchronous) - NOT IMPLEMENTED
282
* @param {string} path - Symbolic link path
283
* @param {function} callback - Callback function receiving (err, linkString)
284
*/
285
readlink(path, callback);
286
```
287
288
## Types
289
290
### Stat Object
291
292
```javascript { .api }
293
/**
294
* File/directory statistics object returned by statSync() and stat()
295
*/
296
interface StatObject {
297
isFile(): boolean; // Returns true if path is a file
298
isDirectory(): boolean; // Returns true if path is a directory
299
isBlockDevice(): boolean; // Always returns false
300
isCharacterDevice(): boolean; // Always returns false
301
isSymbolicLink(): boolean; // Always returns false
302
isFIFO(): boolean; // Always returns false
303
isSocket(): boolean; // Always returns false
304
}
305
```
306
307
### Stream Types
308
309
```javascript { .api }
310
/**
311
* Readable stream created by createReadStream()
312
*/
313
interface ReadableStream {
314
// Standard Node.js ReadableStream interface
315
on(event: string, listener: function): ReadableStream;
316
pipe(destination: WritableStream): WritableStream;
317
}
318
319
/**
320
* Writable stream created by createWriteStream()
321
*/
322
interface WritableStream {
323
// Standard Node.js WritableStream interface
324
write(chunk: string|Buffer, encoding?: string, callback?: function): boolean;
325
end(chunk?: string|Buffer, encoding?: string, callback?: function): void;
326
}
327
```
328
329
## Error Handling
330
331
memory-fs uses errno-compatible error codes through the MemoryFileSystemError class:
332
333
```javascript { .api }
334
/**
335
* Custom error class for filesystem operations
336
* @param {Object} err - Error object with code and description
337
* @param {string} path - File path that caused the error
338
* @param {string} operation - Operation that failed
339
*/
340
class MemoryFileSystemError extends Error {
341
constructor(err, path, operation);
342
343
name: string; // Error name ("MemoryFileSystemError")
344
message: string; // Formatted error message
345
code: string; // Error code (ENOENT, EISDIR, ENOTDIR, etc.)
346
errno: number; // Error number
347
path: string; // Path that caused the error
348
operation: string; // Operation that failed
349
}
350
```
351
352
**Common Error Codes:**
353
- `ENOENT`: File or directory does not exist
354
- `EISDIR`: Operation expected a file but found a directory
355
- `ENOTDIR`: Operation expected a directory but found a file
356
- `EEXIST`: File or directory already exists
357
- `EPERM`: Operation not permitted
358
- `ENOSYS`: Function not implemented (readlink operations)
359
360
## Key Features
361
362
- **Cross-platform paths**: Supports both POSIX (`/path/to/file`) and Windows (`C:\\path\\to\\file`) style paths
363
- **Node.js compatibility**: API closely mirrors Node.js fs module with familiar method names and signatures
364
- **Error compatibility**: Uses errno-compatible error codes for consistent error handling
365
- **Stream support**: Provides readable and writable streams for large file operations
366
- **Encoding support**: Handles various text encodings for string/Buffer conversion
367
- **Recursive operations**: `mkdirpSync()` creates parent directories automatically
368
- **In-memory storage**: Files stored as Buffer objects, directories marked with special properties