0
# File Writing
1
2
File writing capabilities including basic write operations, JSON handling, and content appending for creating and modifying files in the mem-fs store.
3
4
## Capabilities
5
6
### Write File Contents
7
8
Write string or buffer contents to files with optional stat information for setting file permissions.
9
10
```typescript { .api }
11
/**
12
* Write string or buffer to file
13
* @param filepath - Target file path
14
* @param contents - File contents as string or Buffer
15
* @param stat - Optional file stat information for permissions
16
* @returns Contents as string
17
*/
18
function write(filepath: string, contents: string | Buffer, stat?: FileStats): string;
19
20
/**
21
* Internal write function for writing file objects directly
22
* @param file - File object to write to the store
23
*/
24
function _write<EditorFile extends MemFsEditorFile>(file: EditorFile): void;
25
26
interface FileStats {
27
/** File mode/permissions (e.g., 0o755 for executable) */
28
mode?: number;
29
}
30
```
31
32
**Usage Examples:**
33
34
```typescript
35
import { create as createMemFs } from "mem-fs";
36
import { create as createEditor } from "mem-fs-editor";
37
38
const store = createMemFs();
39
const fs = createEditor(store);
40
41
// Write string content
42
fs.write("hello.txt", "Hello, World!");
43
44
// Write buffer content
45
const buffer = Buffer.from("Binary data", "utf8");
46
fs.write("data.bin", buffer);
47
48
// Write with file permissions
49
fs.write("script.sh", "#!/bin/bash\necho 'Hello'", { mode: 0o755 });
50
51
// Write complex content
52
const jsContent = `
53
const greeting = "Hello, World!";
54
console.log(greeting);
55
`;
56
fs.write("greeting.js", jsContent);
57
```
58
59
### Write JSON Files
60
61
Write objects as formatted JSON to files with support for custom replacer functions and spacing options.
62
63
```typescript { .api }
64
/**
65
* Write object as JSON to file
66
* @param filepath - Target file path
67
* @param contents - Object to serialize as JSON
68
* @param replacer - JSON.stringify replacer function or array of keys
69
* @param space - Formatting spaces (default: 2)
70
* @returns JSON string that was written
71
*/
72
function writeJSON(
73
filepath: string,
74
contents: any,
75
replacer?: JSONReplacer,
76
space?: string | number
77
): string;
78
79
type JSONReplacer = ((key: string, value: any) => any) | (number | string)[] | null;
80
```
81
82
**Usage Examples:**
83
84
```typescript
85
// Write simple object
86
const packageData = {
87
name: "my-package",
88
version: "1.0.0",
89
dependencies: {
90
lodash: "^4.17.21"
91
}
92
};
93
fs.writeJSON("package.json", packageData);
94
95
// Write with custom spacing
96
fs.writeJSON("config.json", { port: 3000, debug: true }, null, 4);
97
98
// Write with replacer function
99
const data = { password: "secret", username: "admin", settings: {} };
100
fs.writeJSON("public-config.json", data, (key, value) => {
101
return key === "password" ? "[REDACTED]" : value;
102
});
103
104
// Write with specific keys only
105
const user = { id: 1, name: "John", password: "secret", email: "john@example.com" };
106
fs.writeJSON("user-public.json", user, ["id", "name", "email"]);
107
```
108
109
### Extend JSON Files
110
111
Extend existing JSON files by merging new properties with existing content, creating the file if it doesn't exist.
112
113
```typescript { .api }
114
/**
115
* Extend existing JSON file with new properties
116
* @param filepath - Path to JSON file
117
* @param contents - Properties to merge with existing content
118
* @param replacer - JSON.stringify replacer function or array of keys
119
* @param space - Formatting spaces (default: 2)
120
*/
121
function extendJSON(
122
filepath: string,
123
contents?: Record<string, unknown>,
124
replacer?: JSONReplacer,
125
space?: string | number
126
): void;
127
```
128
129
**Usage Examples:**
130
131
```typescript
132
// Extend existing package.json
133
fs.extendJSON("package.json", {
134
scripts: {
135
build: "tsc",
136
test: "jest"
137
},
138
devDependencies: {
139
typescript: "^4.9.0"
140
}
141
});
142
143
// Add new properties to config
144
fs.extendJSON("config.json", {
145
newFeature: true,
146
timeout: 5000
147
});
148
149
// Create file if doesn't exist
150
fs.extendJSON("new-config.json", {
151
created: new Date().toISOString(),
152
version: "1.0.0"
153
});
154
```
155
156
### Append Content to Files
157
158
Append content to existing files with options for creating files, trimming whitespace, and custom separators.
159
160
```typescript { .api }
161
/**
162
* Append content to existing file
163
* @param filepath - Target file path
164
* @param contents - Content to append as string or Buffer
165
* @param options - Append configuration options
166
*/
167
function append(filepath: string, contents: string | Buffer, options?: AppendOptions): void;
168
169
interface AppendOptions {
170
/** Create file if it doesn't exist (default: undefined) */
171
create?: boolean;
172
/** Remove trailing whitespace before appending (default: true) */
173
trimEnd?: boolean;
174
/** Separator to add between existing and new content (default: OS EOL) */
175
separator?: string;
176
}
177
```
178
179
**Usage Examples:**
180
181
```typescript
182
// Simple append
183
fs.write("log.txt", "Initial log entry");
184
fs.append("log.txt", "\nSecond log entry");
185
186
// Append with newline separator
187
fs.append("log.txt", "Third entry", { separator: "\n" });
188
189
// Append to new file
190
fs.append("new-log.txt", "First entry in new file", { create: true });
191
192
// Append with trimming
193
fs.write("content.txt", "Hello World ");
194
fs.append("content.txt", "!", { trimEnd: true });
195
// Result: "Hello World!"
196
197
// Build up a file with multiple appends
198
fs.write("script.sh", "#!/bin/bash\n");
199
fs.append("script.sh", "echo 'Starting script'", { separator: "\n" });
200
fs.append("script.sh", "echo 'Processing...'", { separator: "\n" });
201
fs.append("script.sh", "echo 'Done!'", { separator: "\n" });
202
```
203
204
## Content Type Handling
205
206
The writing functions automatically handle different content types:
207
208
```typescript
209
// String content
210
fs.write("text.txt", "Plain text content");
211
212
// Buffer content
213
const imageBuffer = Buffer.from([0x89, 0x50, 0x4E, 0x47]);
214
fs.write("image.png", imageBuffer);
215
216
// JSON objects
217
fs.writeJSON("data.json", { items: [1, 2, 3] });
218
219
// Mixed append operations
220
fs.write("mixed.txt", "Initial content");
221
fs.append("mixed.txt", Buffer.from("\nBinary data follows"));
222
```
223
224
## File Permissions
225
226
Use the `stat` parameter in the `write` function to set file permissions:
227
228
```typescript
229
// Make file executable
230
fs.write("script.sh", "#!/bin/bash\necho 'Hello'", { mode: 0o755 });
231
232
// Read-only file
233
fs.write("readonly.txt", "Important data", { mode: 0o444 });
234
235
// Standard file permissions
236
fs.write("regular.txt", "Regular file", { mode: 0o644 });
237
```