0
# Tree & File System Operations
1
2
Core virtual file system interface for reading, writing, and manipulating files during code generation and workspace modifications. The Tree interface provides a virtual view of the filesystem that batches changes and applies them atomically.
3
4
## Capabilities
5
6
### Tree Interface
7
8
The main interface for all file system operations during code generation.
9
10
```typescript { .api }
11
/**
12
* Virtual file system tree for batching file operations
13
*/
14
interface Tree {
15
/** Root directory of the workspace - all paths are relative to this */
16
root: string;
17
/**
18
* Read file contents as Buffer
19
* @param filePath - Path to the file to read
20
* @returns File contents as Buffer or null if file doesn't exist
21
*/
22
read(filePath: string): Buffer | null;
23
24
/**
25
* Read file contents as string with specified encoding
26
* @param filePath - Path to the file to read
27
* @param encoding - Character encoding for the file
28
* @returns File contents as string or null if file doesn't exist
29
*/
30
read(filePath: string, encoding: BufferEncoding): string | null;
31
32
/**
33
* Write content to a file
34
* @param filePath - Path where to write the file
35
* @param content - File content as Buffer or string
36
* @param options - Optional write options
37
*/
38
write(filePath: string, content: Buffer | string, options?: TreeWriteOptions): void;
39
40
/**
41
* Check if a file or directory exists
42
* @param filePath - Path to check
43
* @returns True if file exists, false otherwise
44
*/
45
exists(filePath: string): boolean;
46
47
/**
48
* Delete a file
49
* @param filePath - Path to the file to delete
50
*/
51
delete(filePath: string): void;
52
53
/**
54
* Rename a file or directory
55
* @param from - Current path
56
* @param to - New path
57
*/
58
rename(from: string, to: string): void;
59
60
/**
61
* Check if path is a file (not a directory)
62
* @param filePath - Path to check
63
* @returns True if path is a file, false if directory or doesn't exist
64
*/
65
isFile(filePath: string): boolean;
66
67
/**
68
* List immediate children of a directory
69
* @param dirPath - Directory path
70
* @returns Array of child names (not full paths)
71
*/
72
children(dirPath: string): string[];
73
74
/**
75
* List all changes made to the tree
76
* @returns Array of file changes
77
*/
78
listChanges(): FileChange[];
79
80
/**
81
* Change file permissions
82
* @param filePath - Path to the file
83
* @param mode - New file mode/permissions
84
*/
85
changePermissions(filePath: string, mode: Mode): void;
86
}
87
88
/**
89
* Represents a change to a file in the tree
90
*/
91
interface FileChange {
92
/** Path to the changed file */
93
path: string;
94
/** Type of change */
95
type: 'CREATE' | 'UPDATE' | 'DELETE';
96
/** New content for CREATE/UPDATE operations */
97
content?: Buffer;
98
}
99
100
/**
101
* Options for writing files to the tree
102
*/
103
interface TreeWriteOptions {
104
/** File permissions mode */
105
mode?: Mode;
106
}
107
108
/**
109
* File permission mode
110
*/
111
type Mode = string | number;
112
```
113
114
**Usage Examples:**
115
116
```typescript
117
import { Tree } from "@nrwl/devkit";
118
119
function myGenerator(tree: Tree) {
120
// Read an existing file
121
const packageJson = tree.read('package.json', 'utf-8');
122
if (packageJson) {
123
const config = JSON.parse(packageJson);
124
// Modify config...
125
}
126
127
// Write a new file
128
tree.write('src/new-file.ts', `
129
export const message = 'Hello World';
130
`);
131
132
// Check if file exists before reading
133
if (tree.exists('tsconfig.json')) {
134
const tsConfig = tree.read('tsconfig.json', 'utf-8');
135
// Process tsconfig...
136
}
137
138
// List directory contents
139
const srcFiles = tree.children('src');
140
console.log('Files in src:', srcFiles);
141
142
// Rename a file
143
tree.rename('old-file.ts', 'new-file.ts');
144
145
// Delete a file
146
tree.delete('unwanted-file.ts');
147
}
148
```
149
150
### File Globbing
151
152
Functions for finding files that match specific patterns.
153
154
```typescript { .api }
155
/**
156
* Find files matching a glob pattern synchronously
157
* @param tree - Virtual file system tree
158
* @param patterns - Glob patterns to match
159
* @returns Array of matching file paths
160
*/
161
function glob(tree: Tree, patterns: string[]): string[];
162
163
/**
164
* Find files matching a glob pattern asynchronously
165
* @param tree - Virtual file system tree
166
* @param patterns - Glob patterns to match
167
* @returns Promise resolving to array of matching file paths
168
*/
169
function globAsync(tree: Tree, patterns: string[]): Promise<string[]>;
170
```
171
172
**Usage Examples:**
173
174
```typescript
175
import { Tree, glob, globAsync } from "@nrwl/devkit";
176
177
function findFiles(tree: Tree) {
178
// Find all TypeScript files
179
const tsFiles = glob(tree, ['**/*.ts']);
180
181
// Find test files
182
const testFiles = glob(tree, ['**/*.spec.ts', '**/*.test.ts']);
183
184
// Async globbing
185
const jsFiles = await globAsync(tree, ['**/*.js', '**/*.jsx']);
186
}
187
```
188
189
### File Visiting
190
191
Utility for applying operations to files while respecting ignore patterns.
192
193
```typescript { .api }
194
/**
195
* Visit all files that are not ignored by .gitignore patterns
196
* @param tree - Virtual file system tree
197
* @param dirPath - Directory to start from
198
* @param callback - Function to call for each file
199
*/
200
function visitNotIgnoredFiles(
201
tree: Tree,
202
dirPath: string,
203
callback: (path: string) => void
204
): void;
205
```
206
207
**Usage Examples:**
208
209
```typescript
210
import { Tree, visitNotIgnoredFiles } from "@nrwl/devkit";
211
212
function processAllFiles(tree: Tree) {
213
visitNotIgnoredFiles(tree, '.', (filePath) => {
214
if (filePath.endsWith('.ts')) {
215
const content = tree.read(filePath, 'utf-8');
216
// Process TypeScript files...
217
}
218
});
219
}
220
```