0
# File System APIs
1
2
File management operations for reading, writing, and managing local files in Taro React Native applications.
3
4
## Capabilities
5
6
### File System Manager
7
8
Get a file system manager instance for comprehensive file operations.
9
10
```typescript { .api }
11
/**
12
* Get file system manager instance
13
* @returns FileSystemManager instance
14
*/
15
function getFileSystemManager(): FileSystemManager;
16
17
interface FileSystemManager {
18
/**
19
* Read file content
20
* @param options Read file options
21
*/
22
readFile(options: {
23
filePath: string;
24
encoding?: 'ascii' | 'base64' | 'binary' | 'hex' | 'ucs2' | 'ucs-2' | 'utf16le' | 'utf-16le' | 'utf8' | 'utf-8' | 'latin1';
25
position?: number;
26
length?: number;
27
success?: (res: { data: string | ArrayBuffer }) => void;
28
fail?: (res: TaroGeneral.CallbackResult) => void;
29
complete?: (res: any) => void;
30
}): Promise<{ data: string | ArrayBuffer }>;
31
32
/**
33
* Write file content
34
* @param options Write file options
35
*/
36
writeFile(options: {
37
filePath: string;
38
data: string | ArrayBuffer;
39
encoding?: 'ascii' | 'base64' | 'binary' | 'hex' | 'ucs2' | 'ucs-2' | 'utf16le' | 'utf-16le' | 'utf8' | 'utf-8' | 'latin1';
40
success?: (res: TaroGeneral.CallbackResult) => void;
41
fail?: (res: TaroGeneral.CallbackResult) => void;
42
complete?: (res: TaroGeneral.CallbackResult) => void;
43
}): Promise<TaroGeneral.CallbackResult>;
44
45
/**
46
* Copy file
47
* @param options Copy file options
48
*/
49
copyFile(options: {
50
srcPath: string;
51
destPath: string;
52
success?: (res: TaroGeneral.CallbackResult) => void;
53
fail?: (res: TaroGeneral.CallbackResult) => void;
54
complete?: (res: TaroGeneral.CallbackResult) => void;
55
}): Promise<TaroGeneral.CallbackResult>;
56
57
/**
58
* Move/rename file
59
* @param options Rename file options
60
*/
61
rename(options: {
62
oldPath: string;
63
newPath: string;
64
success?: (res: TaroGeneral.CallbackResult) => void;
65
fail?: (res: TaroGeneral.CallbackResult) => void;
66
complete?: (res: TaroGeneral.CallbackResult) => void;
67
}): Promise<TaroGeneral.CallbackResult>;
68
69
/**
70
* Delete file
71
* @param options Unlink file options
72
*/
73
unlink(options: {
74
filePath: string;
75
success?: (res: TaroGeneral.CallbackResult) => void;
76
fail?: (res: TaroGeneral.CallbackResult) => void;
77
complete?: (res: TaroGeneral.CallbackResult) => void;
78
}): Promise<TaroGeneral.CallbackResult>;
79
80
/**
81
* Get file stats
82
* @param options Get file stats options
83
*/
84
stat(options: {
85
path: string;
86
recursive?: boolean;
87
success?: (res: {
88
stats: Stats | Record<string, Stats>;
89
}) => void;
90
fail?: (res: TaroGeneral.CallbackResult) => void;
91
complete?: (res: any) => void;
92
}): Promise<{ stats: Stats | Record<string, Stats> }>;
93
94
/**
95
* Create directory
96
* @param options Make directory options
97
*/
98
mkdir(options: {
99
dirPath: string;
100
recursive?: boolean;
101
success?: (res: TaroGeneral.CallbackResult) => void;
102
fail?: (res: TaroGeneral.CallbackResult) => void;
103
complete?: (res: TaroGeneral.CallbackResult) => void;
104
}): Promise<TaroGeneral.CallbackResult>;
105
106
/**
107
* Remove directory
108
* @param options Remove directory options
109
*/
110
rmdir(options: {
111
dirPath: string;
112
recursive?: boolean;
113
success?: (res: TaroGeneral.CallbackResult) => void;
114
fail?: (res: TaroGeneral.CallbackResult) => void;
115
complete?: (res: TaroGeneral.CallbackResult) => void;
116
}): Promise<TaroGeneral.CallbackResult>;
117
118
/**
119
* Read directory contents
120
* @param options Read directory options
121
*/
122
readdir(options: {
123
dirPath: string;
124
success?: (res: { files: string[] }) => void;
125
fail?: (res: TaroGeneral.CallbackResult) => void;
126
complete?: (res: any) => void;
127
}): Promise<{ files: string[] }>;
128
129
/**
130
* Check if file/directory exists
131
* @param options Access check options
132
*/
133
access(options: {
134
path: string;
135
success?: (res: TaroGeneral.CallbackResult) => void;
136
fail?: (res: TaroGeneral.CallbackResult) => void;
137
complete?: (res: TaroGeneral.CallbackResult) => void;
138
}): Promise<TaroGeneral.CallbackResult>;
139
}
140
141
interface Stats {
142
mode: number;
143
size: number;
144
lastAccessedTime: number;
145
lastModifiedTime: number;
146
isDirectory(): boolean;
147
isFile(): boolean;
148
}
149
```
150
151
**Usage Examples:**
152
153
```typescript
154
import { getFileSystemManager } from "@tarojs/taro-rn";
155
156
const fs = getFileSystemManager();
157
158
// Write text file
159
await fs.writeFile({
160
filePath: '/data/user_data.txt',
161
data: 'Hello, World!',
162
encoding: 'utf8'
163
});
164
165
// Read text file
166
const textResult = await fs.readFile({
167
filePath: '/data/user_data.txt',
168
encoding: 'utf8'
169
});
170
console.log('File content:', textResult.data);
171
172
// Write binary file
173
const binaryData = new ArrayBuffer(1024);
174
await fs.writeFile({
175
filePath: '/data/binary_file.bin',
176
data: binaryData
177
});
178
179
// Create directory
180
await fs.mkdir({
181
dirPath: '/data/images',
182
recursive: true
183
});
184
185
// Copy file
186
await fs.copyFile({
187
srcPath: '/data/user_data.txt',
188
destPath: '/data/backup/user_data_backup.txt'
189
});
190
191
// Get file info
192
const statResult = await fs.stat({
193
path: '/data/user_data.txt'
194
});
195
196
const stats = statResult.stats as Stats;
197
console.log('File size:', stats.size);
198
console.log('Is file:', stats.isFile());
199
console.log('Last modified:', new Date(stats.lastModifiedTime));
200
```
201
202
### Saved File Management
203
204
Manage saved files with metadata and persistent storage.
205
206
```typescript { .api }
207
/**
208
* Save file to persistent storage
209
* @param options Save file options
210
*/
211
function saveFile(options: {
212
tempFilePath: string;
213
filePath?: string;
214
success?: (res: {
215
savedFilePath: string;
216
}) => void;
217
fail?: (res: TaroGeneral.CallbackResult) => void;
218
complete?: (res: any) => void;
219
}): Promise<{
220
savedFilePath: string;
221
}>;
222
223
/**
224
* Get list of saved files
225
* @param options Get saved file list options
226
*/
227
function getSavedFileList(options?: {
228
success?: (res: {
229
fileList: {
230
filePath: string;
231
createTime: number;
232
size: number;
233
}[];
234
}) => void;
235
fail?: (res: TaroGeneral.CallbackResult) => void;
236
complete?: (res: any) => void;
237
}): Promise<{
238
fileList: {
239
filePath: string;
240
createTime: number;
241
size: number;
242
}[];
243
}>;
244
245
/**
246
* Get saved file information
247
* @param options Get saved file info options
248
*/
249
function getSavedFileInfo(options: {
250
filePath: string;
251
success?: (res: {
252
createTime: number;
253
size: number;
254
}) => void;
255
fail?: (res: TaroGeneral.CallbackResult) => void;
256
complete?: (res: any) => void;
257
}): Promise<{
258
createTime: number;
259
size: number;
260
}>;
261
262
/**
263
* Remove saved file
264
* @param options Remove saved file options
265
*/
266
function removeSavedFile(options: {
267
filePath: string;
268
success?: (res: TaroGeneral.CallbackResult) => void;
269
fail?: (res: TaroGeneral.CallbackResult) => void;
270
complete?: (res: TaroGeneral.CallbackResult) => void;
271
}): Promise<TaroGeneral.CallbackResult>;
272
```
273
274
### File Information
275
276
Get detailed file information and metadata.
277
278
```typescript { .api }
279
/**
280
* Get file information
281
* @param options Get file info options
282
*/
283
function getFileInfo(options: {
284
filePath: string;
285
digestAlgorithm?: 'md5' | 'sha1';
286
success?: (res: {
287
size: number;
288
digest?: string;
289
}) => void;
290
fail?: (res: TaroGeneral.CallbackResult) => void;
291
complete?: (res: any) => void;
292
}): Promise<{
293
size: number;
294
digest?: string;
295
}>;
296
```
297
298
### URL Operations
299
300
Open URLs and external applications.
301
302
```typescript { .api }
303
/**
304
* Open URL in external browser or application
305
* @param options Open URL options
306
*/
307
function openUrl(options: {
308
url: string;
309
success?: (res: TaroGeneral.CallbackResult) => void;
310
fail?: (res: TaroGeneral.CallbackResult) => void;
311
complete?: (res: TaroGeneral.CallbackResult) => void;
312
}): Promise<TaroGeneral.CallbackResult>;
313
```
314
315
**Usage Examples:**
316
317
```typescript
318
import {
319
saveFile,
320
getSavedFileList,
321
getSavedFileInfo,
322
removeSavedFile,
323
getFileInfo,
324
openUrl
325
} from "@tarojs/taro-rn";
326
327
// Save a temporary file permanently
328
const saveResult = await saveFile({
329
tempFilePath: '/tmp/photo_12345.jpg'
330
});
331
console.log('File saved to:', saveResult.savedFilePath);
332
333
// Get all saved files
334
const savedFiles = await getSavedFileList();
335
console.log('Saved files:', savedFiles.fileList);
336
337
// Get info for specific saved file
338
const fileInfo = await getSavedFileInfo({
339
filePath: saveResult.savedFilePath
340
});
341
console.log('File created:', new Date(fileInfo.createTime));
342
console.log('File size:', fileInfo.size);
343
344
// Get file info with digest
345
const detailedInfo = await getFileInfo({
346
filePath: saveResult.savedFilePath,
347
digestAlgorithm: 'md5'
348
});
349
console.log('File MD5:', detailedInfo.digest);
350
351
// Remove saved file
352
await removeSavedFile({
353
filePath: saveResult.savedFilePath
354
});
355
356
// Open external URL
357
await openUrl({
358
url: 'https://www.example.com'
359
});
360
361
// Open native app
362
await openUrl({
363
url: 'mailto:user@example.com?subject=Hello'
364
});
365
```
366
367
## File Management Patterns
368
369
### Directory Operations
370
371
```typescript
372
import { getFileSystemManager } from "@tarojs/taro-rn";
373
374
const fs = getFileSystemManager();
375
376
// Create nested directory structure
377
async function createDirectoryStructure() {
378
await fs.mkdir({ dirPath: '/data/app/cache', recursive: true });
379
await fs.mkdir({ dirPath: '/data/app/logs', recursive: true });
380
await fs.mkdir({ dirPath: '/data/app/temp', recursive: true });
381
}
382
383
// List directory contents recursively
384
async function listDirectoryRecursive(dirPath: string): Promise<string[]> {
385
const result = await fs.readdir({ dirPath });
386
const allFiles: string[] = [];
387
388
for (const file of result.files) {
389
const fullPath = `${dirPath}/${file}`;
390
const stats = await fs.stat({ path: fullPath });
391
392
if ((stats.stats as Stats).isDirectory()) {
393
const subFiles = await listDirectoryRecursive(fullPath);
394
allFiles.push(...subFiles);
395
} else {
396
allFiles.push(fullPath);
397
}
398
}
399
400
return allFiles;
401
}
402
403
// Clean up old files
404
async function cleanupOldFiles(dirPath: string, maxAge: number) {
405
const files = await listDirectoryRecursive(dirPath);
406
const now = Date.now();
407
408
for (const filePath of files) {
409
try {
410
const stats = await fs.stat({ path: filePath });
411
const fileStats = stats.stats as Stats;
412
413
if (now - fileStats.lastModifiedTime > maxAge) {
414
await fs.unlink({ filePath });
415
console.log('Deleted old file:', filePath);
416
}
417
} catch (error) {
418
console.warn('Failed to process file:', filePath, error);
419
}
420
}
421
}
422
```
423
424
### Data Serialization
425
426
```typescript
427
import { getFileSystemManager } from "@tarojs/taro-rn";
428
429
const fs = getFileSystemManager();
430
431
// Save JSON data
432
async function saveJsonData(filePath: string, data: any) {
433
const jsonString = JSON.stringify(data, null, 2);
434
await fs.writeFile({
435
filePath,
436
data: jsonString,
437
encoding: 'utf8'
438
});
439
}
440
441
// Load JSON data
442
async function loadJsonData(filePath: string): Promise<any> {
443
try {
444
const result = await fs.readFile({
445
filePath,
446
encoding: 'utf8'
447
});
448
return JSON.parse(result.data as string);
449
} catch (error) {
450
console.warn('Failed to load JSON data:', error);
451
return null;
452
}
453
}
454
455
// Save binary data with metadata
456
async function saveBinaryWithMetadata(filePath: string, data: ArrayBuffer, metadata: any) {
457
// Save binary data
458
await fs.writeFile({ filePath, data });
459
460
// Save metadata as JSON
461
const metadataPath = filePath + '.meta';
462
await saveJsonData(metadataPath, {
463
...metadata,
464
size: data.byteLength,
465
createdAt: Date.now()
466
});
467
}
468
469
// Usage
470
const userData = { id: 123, name: 'John', preferences: { theme: 'dark' } };
471
await saveJsonData('/data/user.json', userData);
472
473
const loadedData = await loadJsonData('/data/user.json');
474
console.log('Loaded user data:', loadedData);
475
```