0
# File System Commands
1
2
Server-side file operations accessible from browser context for reading configuration files, test fixtures, and writing test outputs, bridging browser and server file systems.
3
4
## Capabilities
5
6
### File Reading
7
8
Read files from the server file system during browser tests.
9
10
```typescript { .api }
11
/**
12
* Read file from server filesystem
13
* @param path - File path relative to server working directory
14
* @param options - Encoding or file system options
15
* @returns Promise resolving to file content as string
16
*/
17
readFile(path: string, options?: BufferEncoding | FsOptions): Promise<string>;
18
```
19
20
**Usage Examples:**
21
22
```typescript
23
import { commands } from "@vitest/browser/context";
24
25
// Read configuration files
26
const configContent = await commands.readFile("./config.json");
27
const config = JSON.parse(configContent);
28
29
// Read test fixtures
30
const fixtureData = await commands.readFile("./fixtures/test-data.json");
31
const testData = JSON.parse(fixtureData);
32
33
// Read with specific encoding
34
const textContent = await commands.readFile("./data.txt", "utf8");
35
const binaryContent = await commands.readFile("./image.png", "base64");
36
37
// Read with file system options
38
const content = await commands.readFile("./file.txt", {
39
encoding: "utf8",
40
flag: "r"
41
});
42
43
// Handle different file types
44
const csvData = await commands.readFile("./data.csv");
45
const csvRows = csvData.split('\n').map(row => row.split(','));
46
47
const xmlData = await commands.readFile("./config.xml");
48
const parser = new DOMParser();
49
const xmlDoc = parser.parseFromString(xmlData, "text/xml");
50
```
51
52
### File Writing
53
54
Write files to the server file system from browser tests.
55
56
```typescript { .api }
57
/**
58
* Write file to server filesystem
59
* @param path - File path relative to server working directory
60
* @param content - Content to write to file
61
* @param options - Encoding or file system options with optional mode
62
* @returns Promise that resolves when file is written
63
*/
64
writeFile(path: string, content: string, options?: BufferEncoding | (FsOptions & { mode?: number | string })): Promise<void>;
65
```
66
67
**Usage Examples:**
68
69
```typescript
70
import { commands } from "@vitest/browser/context";
71
72
// Write test results
73
const testResults = {
74
passed: 15,
75
failed: 2,
76
timestamp: new Date().toISOString()
77
};
78
await commands.writeFile("./test-results.json", JSON.stringify(testResults, null, 2));
79
80
// Write logs
81
const logEntry = `${new Date().toISOString()}: Test completed\n`;
82
await commands.writeFile("./test.log", logEntry, { flag: "a" }); // append mode
83
84
// Write CSV data
85
const csvData = [
86
["Name", "Age", "City"],
87
["John", "30", "New York"],
88
["Jane", "25", "Boston"]
89
];
90
const csvContent = csvData.map(row => row.join(',')).join('\n');
91
await commands.writeFile("./output.csv", csvContent);
92
93
// Write with specific encoding and permissions
94
await commands.writeFile("./config.txt", "sensitive data", {
95
encoding: "utf8",
96
mode: 0o600 // Read/write for owner only
97
});
98
99
// Write binary data (base64 encoded)
100
const imageBase64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";
101
const imageData = imageBase64.split(',')[1]; // Remove data URL prefix
102
await commands.writeFile("./test-image.png", imageData, "base64");
103
```
104
105
### File Removal
106
107
Delete files from the server file system.
108
109
```typescript { .api }
110
/**
111
* Remove file from server filesystem
112
* @param path - File path relative to server working directory
113
* @returns Promise that resolves when file is deleted
114
*/
115
removeFile(path: string): Promise<void>;
116
```
117
118
**Usage Examples:**
119
120
```typescript
121
import { commands } from "@vitest/browser/context";
122
123
// Clean up test files
124
await commands.removeFile("./temp-test-file.txt");
125
await commands.removeFile("./output.json");
126
127
// Conditional cleanup
128
const fileExists = await commands.readFile("./optional-file.txt")
129
.then(() => true)
130
.catch(() => false);
131
132
if (fileExists) {
133
await commands.removeFile("./optional-file.txt");
134
}
135
136
// Bulk cleanup
137
const testFiles = [
138
"./temp1.txt",
139
"./temp2.json",
140
"./temp3.csv"
141
];
142
143
for (const file of testFiles) {
144
try {
145
await commands.removeFile(file);
146
} catch (error) {
147
console.warn(`Could not remove ${file}:`, error);
148
}
149
}
150
```
151
152
### Advanced File Operations
153
154
Complex file manipulation patterns for testing scenarios.
155
156
**Configuration Management:**
157
158
```typescript
159
import { commands } from "@vitest/browser/context";
160
161
// Read, modify, and write config
162
const configPath = "./test-config.json";
163
const originalConfig = JSON.parse(await commands.readFile(configPath));
164
165
const testConfig = {
166
...originalConfig,
167
testMode: true,
168
apiUrl: "http://localhost:3001"
169
};
170
171
await commands.writeFile(configPath, JSON.stringify(testConfig, null, 2));
172
173
// Test with modified config...
174
175
// Restore original config
176
await commands.writeFile(configPath, JSON.stringify(originalConfig, null, 2));
177
```
178
179
**Test Data Generation:**
180
181
```typescript
182
// Generate test data files
183
const generateTestData = async (userCount: number) => {
184
const users = Array.from({ length: userCount }, (_, i) => ({
185
id: i + 1,
186
name: `User ${i + 1}`,
187
email: `user${i + 1}@example.com`
188
}));
189
190
await commands.writeFile("./test-users.json", JSON.stringify(users, null, 2));
191
192
// Generate CSV version
193
const csvHeader = "id,name,email\n";
194
const csvRows = users.map(u => `${u.id},${u.name},${u.email}`).join('\n');
195
await commands.writeFile("./test-users.csv", csvHeader + csvRows);
196
};
197
198
await generateTestData(100);
199
```
200
201
**Log Analysis:**
202
203
```typescript
204
// Analyze test logs
205
const logContent = await commands.readFile("./application.log");
206
const logLines = logContent.split('\n');
207
208
const errors = logLines.filter(line => line.includes('ERROR'));
209
const warnings = logLines.filter(line => line.includes('WARN'));
210
211
const logSummary = {
212
totalLines: logLines.length,
213
errors: errors.length,
214
warnings: warnings.length,
215
errorMessages: errors.slice(0, 10) // First 10 errors
216
};
217
218
await commands.writeFile("./log-summary.json", JSON.stringify(logSummary, null, 2));
219
```
220
221
**File Upload Testing:**
222
223
```typescript
224
// Create test files for upload scenarios
225
const createTestFiles = async () => {
226
// Text file
227
await commands.writeFile("./upload-test.txt", "This is a test file for upload");
228
229
// JSON file
230
const jsonData = { test: true, data: [1, 2, 3] };
231
await commands.writeFile("./upload-test.json", JSON.stringify(jsonData));
232
233
// CSV file
234
const csvContent = "name,value\ntest1,100\ntest2,200";
235
await commands.writeFile("./upload-test.csv", csvContent);
236
};
237
238
await createTestFiles();
239
240
// Test file upload functionality
241
const fileInput = page.getByLabelText("Upload file");
242
await userEvent.upload(fileInput, ["./upload-test.txt"]);
243
244
// Cleanup after test
245
await commands.removeFile("./upload-test.txt");
246
await commands.removeFile("./upload-test.json");
247
await commands.removeFile("./upload-test.csv");
248
```
249
250
### Error Handling
251
252
Handle file system errors gracefully in browser tests.
253
254
```typescript
255
import { commands } from "@vitest/browser/context";
256
257
// Safe file reading with fallback
258
const readConfigSafely = async (configPath: string, defaultConfig: object) => {
259
try {
260
const content = await commands.readFile(configPath);
261
return JSON.parse(content);
262
} catch (error) {
263
console.warn(`Could not read config from ${configPath}, using default`);
264
return defaultConfig;
265
}
266
};
267
268
// Ensure directory exists (by writing a marker file)
269
const ensureTestDir = async () => {
270
try {
271
await commands.writeFile("./test-output/.gitkeep", "");
272
} catch (error) {
273
console.error("Could not create test output directory");
274
throw error;
275
}
276
};
277
278
// Atomic file operations
279
const writeFileSafely = async (path: string, content: string) => {
280
const tempPath = `${path}.tmp`;
281
282
try {
283
// Write to temporary file first
284
await commands.writeFile(tempPath, content);
285
286
// Remove original file
287
try {
288
await commands.removeFile(path);
289
} catch {
290
// Original file might not exist
291
}
292
293
// Move temp file to final location (rename not available, so re-write)
294
const tempContent = await commands.readFile(tempPath);
295
await commands.writeFile(path, tempContent);
296
await commands.removeFile(tempPath);
297
} catch (error) {
298
// Cleanup temp file on error
299
try {
300
await commands.removeFile(tempPath);
301
} catch {
302
// Ignore cleanup errors
303
}
304
throw error;
305
}
306
};
307
```
308
309
### Path Handling
310
311
File paths are relative to the server's working directory (where the test runner is executed).
312
313
```typescript
314
// Examples of valid paths:
315
await commands.readFile("./config.json"); // Current directory
316
await commands.readFile("../parent-config.json"); // Parent directory
317
await commands.readFile("subdir/file.txt"); // Subdirectory
318
await commands.readFile("fixtures/test-data.json"); // Test fixtures
319
320
// Absolute paths work but are not recommended:
321
// await commands.readFile("/absolute/path/file.txt");
322
323
// Path construction for cross-platform compatibility
324
const configPath = "./config.json";
325
const logPath = "./logs/test.log";
326
const fixturePath = "./fixtures/user-data.json";
327
```
328
329
## Types
330
331
File system operation types and options:
332
333
```typescript { .api }
334
/**
335
* Buffer encoding options for file operations
336
*/
337
type BufferEncoding =
338
| 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'utf-16le'
339
| 'ucs2' | 'ucs-2' | 'base64' | 'base64url'
340
| 'latin1' | 'binary' | 'hex';
341
342
/**
343
* File system operation options
344
*/
345
interface FsOptions {
346
/** Text encoding for file content */
347
encoding?: BufferEncoding;
348
/** File system flag (e.g., 'r', 'w', 'a') */
349
flag?: string | number;
350
}
351
352
/**
353
* Browser commands interface
354
*/
355
interface BrowserCommands {
356
readFile(path: string, options?: BufferEncoding | FsOptions): Promise<string>;
357
writeFile(path: string, content: string, options?: BufferEncoding | (FsOptions & { mode?: number | string })): Promise<void>;
358
removeFile(path: string): Promise<void>;
359
}
360
```