0
# File System Operations
1
2
The Tree interface provides a virtual file system for generators and executors, enabling safe file manipulation with change tracking and batching capabilities.
3
4
## Capabilities
5
6
### Tree Interface
7
8
The core interface for all file system operations in Nx generators and executors.
9
10
```typescript { .api }
11
/**
12
* Virtual file system interface for generators and executors
13
* Tracks all changes for safe batching and rollback capabilities
14
*/
15
interface Tree {
16
/** Root directory of the workspace */
17
root: string;
18
/** Read file contents as buffer or string */
19
read(filePath: string): Buffer | null;
20
read(filePath: string, encoding: BufferEncoding): string | null;
21
/** Write content to a file (creates or updates) */
22
write(
23
filePath: string,
24
content: Buffer | string,
25
options?: TreeWriteOptions
26
): void;
27
/** Check if a file exists */
28
exists(filePath: string): boolean;
29
/** Delete a file */
30
delete(filePath: string): void;
31
/** Rename/move a file or directory */
32
rename(from: string, to: string): void;
33
/** Check if a path is a file (not a directory) */
34
isFile(filePath: string): boolean;
35
/** Get list of children of a directory */
36
children(dirPath: string): string[];
37
/** Get list of all changes made to the tree */
38
listChanges(): FileChange[];
39
/** Change file permissions */
40
changePermissions(filePath: string, mode: Mode): void;
41
}
42
43
interface TreeWriteOptions {
44
/** File permissions (e.g., '755' or 0o755) */
45
mode?: Mode;
46
}
47
48
type Mode = string | number;
49
50
interface FileChange {
51
/** Path to the changed file */
52
path: string;
53
/** Type of change made */
54
type: "CREATE" | "UPDATE" | "DELETE";
55
/** New content for the file (null for deletions) */
56
content: Buffer | null;
57
/** Optional file write options including permissions */
58
options?: TreeWriteOptions;
59
}
60
```
61
62
**Usage Examples:**
63
64
```typescript
65
import { Tree } from "@nx/devkit";
66
67
export default function myGenerator(tree: Tree) {
68
// Read existing file
69
const packageJson = tree.read("package.json", "utf-8");
70
71
// Create new file with permissions
72
tree.write("src/new-file.ts", `
73
export const greeting = "Hello, World!";
74
`, { mode: '644' });
75
76
// Create executable script
77
tree.write("scripts/build.sh", "#!/bin/bash\nnpm run build", { mode: '755' });
78
79
// Check if file exists before modifying
80
if (tree.exists("README.md")) {
81
const readme = tree.read("README.md", "utf-8");
82
tree.write("README.md", readme + "\n\n## New Section");
83
}
84
85
// Check if path is a file
86
if (tree.isFile("package.json")) {
87
console.log("package.json is a file");
88
}
89
90
// List directory contents
91
const srcFiles = tree.children("src");
92
console.log("Files in src:", srcFiles);
93
94
// Rename files
95
tree.rename("old-config.json", "new-config.json");
96
97
// Change file permissions
98
tree.changePermissions("scripts/deploy.sh", '755');
99
100
// View all changes
101
const changes = tree.listChanges();
102
console.log(`Made ${changes.length} changes`);
103
changes.forEach(change => {
104
console.log(`${change.type}: ${change.path}`);
105
if (change.options?.mode) {
106
console.log(` Mode: ${change.options.mode}`);
107
}
108
});
109
}
110
```
111
112
### JSON File Operations
113
114
Specialized utilities for reading, writing, and updating JSON files with proper parsing and formatting.
115
116
```typescript { .api }
117
/**
118
* Read and parse a JSON file from the tree
119
* @param tree - File system tree
120
* @param path - Path to JSON file
121
* @returns Parsed JSON object
122
*/
123
function readJson<T = any>(tree: Tree, path: string): T;
124
125
/**
126
* Write an object to a JSON file with proper formatting
127
* @param tree - File system tree
128
* @param path - Path to JSON file
129
* @param value - Object to serialize
130
*/
131
function writeJson<T = any>(tree: Tree, path: string, value: T): void;
132
133
/**
134
* Update a JSON file using a callback function
135
* @param tree - File system tree
136
* @param path - Path to JSON file
137
* @param updater - Function to modify the JSON object
138
*/
139
function updateJson<T = any>(
140
tree: Tree,
141
path: string,
142
updater: (value: T) => T
143
): void;
144
```
145
146
**Usage Examples:**
147
148
```typescript
149
import { Tree, readJson, writeJson, updateJson } from "@nx/devkit";
150
151
export default function myGenerator(tree: Tree) {
152
// Read package.json
153
const packageJson = readJson(tree, "package.json");
154
155
// Create new JSON file
156
writeJson(tree, "nx.json", {
157
version: 2,
158
projects: {}
159
});
160
161
// Update existing JSON file
162
updateJson(tree, "package.json", (json) => ({
163
...json,
164
scripts: {
165
...json.scripts,
166
build: "nx build",
167
},
168
}));
169
}
170
```
171
172
### File Pattern Matching
173
174
Utilities for finding files using glob patterns.
175
176
```typescript { .api }
177
/**
178
* Synchronously find files matching glob patterns
179
* @param tree - File system tree
180
* @param patterns - Array of glob patterns
181
* @returns Array of matching file paths
182
*/
183
function glob(tree: Tree, patterns: string[]): string[];
184
185
/**
186
* Asynchronously find files matching glob patterns
187
* @param tree - File system tree
188
* @param patterns - Array of glob patterns
189
* @returns Promise resolving to array of matching file paths
190
*/
191
function globAsync(tree: Tree, patterns: string[]): Promise<string[]>;
192
```
193
194
**Usage Examples:**
195
196
```typescript
197
import { Tree, glob, globAsync } from "@nx/devkit";
198
199
export default async function myGenerator(tree: Tree) {
200
// Find all TypeScript files
201
const tsFiles = glob(tree, ["**/*.ts", "!**/*.spec.ts"]);
202
203
// Find test files asynchronously
204
const testFiles = await globAsync(tree, ["**/*.spec.ts", "**/*.test.ts"]);
205
206
console.log(`Found ${tsFiles.length} TypeScript files`);
207
console.log(`Found ${testFiles.length} test files`);
208
}
209
```
210
211
### File System Utilities
212
213
Additional utilities for working with the file system through the Tree interface.
214
215
```typescript { .api }
216
/**
217
* Visit all files in a directory that are not ignored by git
218
* @param tree - File system tree
219
* @param dirPath - Directory to visit (defaults to root)
220
* @param visitor - Function called for each file
221
*/
222
function visitNotIgnoredFiles(
223
tree: Tree,
224
dirPath: string = "",
225
visitor: (path: string) => void
226
): void;
227
228
/**
229
* Move files from one directory to another
230
* @param tree - File system tree
231
* @param oldDir - Source directory
232
* @param newDir - Target directory
233
*/
234
function moveFilesToNewDirectory(
235
tree: Tree,
236
oldDir: string,
237
newDir: string
238
): void;
239
```
240
241
**Usage Examples:**
242
243
```typescript
244
import { Tree, visitNotIgnoredFiles, moveFilesToNewDirectory } from "@nx/devkit";
245
246
export default function myGenerator(tree: Tree) {
247
// Process all non-ignored files
248
visitNotIgnoredFiles(tree, "src", (filePath) => {
249
if (filePath.endsWith(".ts")) {
250
console.log(`Processing TypeScript file: ${filePath}`);
251
}
252
});
253
254
// Move entire directory
255
moveFilesToNewDirectory(tree, "old-libs/mylib", "libs/mylib");
256
}
257
```
258
259
### Low-level JSON Utilities
260
261
Lower-level JSON parsing and serialization utilities for direct file system operations.
262
263
```typescript { .api }
264
/**
265
* Parse JSON string with comment support
266
* @param input - JSON string to parse
267
* @param options - Parsing options
268
* @returns Parsed object
269
*/
270
function parseJson<T = any>(input: string, options?: JsonParseOptions): T;
271
272
/**
273
* Serialize object to JSON string with formatting
274
* @param input - Object to serialize
275
* @param options - Serialization options
276
* @returns Formatted JSON string
277
*/
278
function serializeJson<T = any>(
279
input: T,
280
options?: JsonSerializeOptions
281
): string;
282
283
/**
284
* Remove comments from JSON string
285
* @param text - JSON string with comments
286
* @returns Clean JSON string
287
*/
288
function stripJsonComments(text: string): string;
289
290
/**
291
* Read and parse JSON file from disk
292
* @param path - File path
293
* @returns Parsed JSON object
294
*/
295
function readJsonFile<T = any>(path: string): T;
296
297
/**
298
* Write object to JSON file on disk
299
* @param path - File path
300
* @param data - Object to write
301
*/
302
function writeJsonFile<T = any>(path: string, data: T): void;
303
304
interface JsonParseOptions {
305
/** Allow trailing commas */
306
allowTrailingComma?: boolean;
307
/** Preserve property order */
308
expectComments?: boolean;
309
}
310
311
interface JsonSerializeOptions {
312
/** Number of spaces for indentation */
313
spaces?: number;
314
/** Preserve property order */
315
replacer?: (key: string, value: any) => any;
316
}
317
```