0
# File System Operations
1
2
Cross-platform file system access for reading, writing, and managing files and folders on mobile devices. The file system API provides both synchronous and asynchronous operations with full path manipulation utilities.
3
4
## Capabilities
5
6
### File System Entity Base
7
8
Base class for all file system objects providing common functionality for files and folders.
9
10
```typescript { .api }
11
/**
12
* Base class for file system entities (files and folders)
13
*/
14
class FileSystemEntity {
15
// Properties
16
readonly name: string;
17
readonly path: string;
18
readonly parent: Folder;
19
readonly lastModified: Date;
20
readonly size: number;
21
readonly isLocked: boolean;
22
23
// Methods
24
remove(): Promise<void>;
25
removeSync(): void;
26
rename(newName: string): Promise<void>;
27
renameSync(newName: string): void;
28
29
// Static factory methods
30
static fromPath(path: string): FileSystemEntity;
31
}
32
```
33
34
### File Operations
35
36
File class providing comprehensive file reading, writing, and manipulation capabilities.
37
38
```typescript { .api }
39
/**
40
* File representation with read/write operations
41
*/
42
class File extends FileSystemEntity {
43
// Static factory methods
44
static fromPath(path: string): File;
45
static exists(path: string): boolean;
46
47
// Text operations (async)
48
readText(encoding?: string): Promise<string>;
49
writeText(content: string, encoding?: string): Promise<void>;
50
51
// Text operations (sync)
52
readTextSync(encoding?: string): string;
53
writeTextSync(content: string, encoding?: string): void;
54
55
// Binary operations (async)
56
read(): Promise<any>;
57
write(data: any): Promise<void>;
58
59
// Binary operations (sync)
60
readSync(): any;
61
writeSync(data: any): void;
62
63
// File-specific properties
64
readonly extension: string;
65
readonly isTextFile: boolean;
66
}
67
```
68
69
**File Usage Examples:**
70
71
```typescript
72
import { File, knownFolders } from "tns-core-modules";
73
74
// Create file reference
75
const documentsFolder = knownFolders.documents();
76
const file = documentsFolder.getFile("mydata.txt");
77
78
// Async text operations
79
async function handleTextFile() {
80
// Write text to file
81
await file.writeText("Hello, NativeScript!");
82
83
// Read text from file
84
const content = await file.readText();
85
console.log("File content:", content);
86
87
// Append text
88
const existingContent = await file.readText();
89
await file.writeText(existingContent + "\nNew line added");
90
}
91
92
// Sync text operations
93
function handleTextFileSync() {
94
// Write and read synchronously
95
file.writeTextSync("Synchronous content");
96
const content = file.readTextSync();
97
console.log("Sync content:", content);
98
}
99
100
// Check if file exists
101
const configFile = File.fromPath("~/config.json");
102
if (File.exists(configFile.path)) {
103
const config = JSON.parse(configFile.readTextSync());
104
}
105
106
// Binary file operations
107
async function handleBinaryFile() {
108
const imageFile = documentsFolder.getFile("image.png");
109
const binaryData = await imageFile.read();
110
111
// Process binary data
112
const newFile = documentsFolder.getFile("copy.png");
113
await newFile.write(binaryData);
114
}
115
```
116
117
### Folder Operations
118
119
Folder class for directory management, navigation, and file enumeration.
120
121
```typescript { .api }
122
/**
123
* Folder representation with directory operations
124
*/
125
class Folder extends FileSystemEntity {
126
// Static factory methods
127
static fromPath(path: string): Folder;
128
static exists(path: string): boolean;
129
130
// Content access
131
getFile(name: string): File;
132
getFolder(name: string): Folder;
133
134
// Enumeration (async)
135
getEntities(): Promise<FileSystemEntity[]>;
136
eachEntity(onEntity: (entity: FileSystemEntity) => boolean): Promise<void>;
137
138
// Enumeration (sync)
139
getEntitiesSync(): FileSystemEntity[];
140
eachEntitySync(onEntity: (entity: FileSystemEntity) => boolean): void;
141
142
// Directory operations
143
clear(): Promise<void>;
144
clearSync(): void;
145
146
// Properties
147
readonly isKnown: boolean;
148
}
149
```
150
151
**Folder Usage Examples:**
152
153
```typescript
154
import { Folder, knownFolders, File } from "tns-core-modules";
155
156
// Access known folders
157
const documents = knownFolders.documents();
158
const temp = knownFolders.temp();
159
const currentApp = knownFolders.currentApp();
160
161
// Create subfolder
162
const dataFolder = documents.getFolder("appData");
163
164
// List folder contents (async)
165
async function listFolderContents(folder: Folder) {
166
const entities = await folder.getEntities();
167
168
entities.forEach(entity => {
169
if (entity instanceof File) {
170
console.log(`File: ${entity.name} (${entity.size} bytes)`);
171
} else if (entity instanceof Folder) {
172
console.log(`Folder: ${entity.name}`);
173
}
174
});
175
}
176
177
// Iterate through entities (async)
178
async function processAllFiles(folder: Folder) {
179
await folder.eachEntity((entity) => {
180
if (entity instanceof File && entity.extension === ".txt") {
181
console.log(`Processing: ${entity.name}`);
182
// Process text file
183
return true; // continue iteration
184
}
185
return true;
186
});
187
}
188
189
// Sync folder operations
190
function syncFolderOperations() {
191
const folder = documents.getFolder("logs");
192
const entities = folder.getEntitiesSync();
193
194
// Process each entity synchronously
195
entities.forEach(entity => {
196
console.log(`Entity: ${entity.name}, Modified: ${entity.lastModified}`);
197
});
198
199
// Clear folder contents
200
folder.clearSync();
201
}
202
```
203
204
### Known Folders
205
206
Pre-defined system folders providing access to standard mobile device directories.
207
208
```typescript { .api }
209
/**
210
* Known system folders namespace
211
*/
212
namespace knownFolders {
213
/**
214
* Application documents folder (user data storage)
215
*/
216
function documents(): Folder;
217
218
/**
219
* Temporary files folder (cleared on app restart)
220
*/
221
function temp(): Folder;
222
223
/**
224
* Current application folder (app bundle/installation)
225
*/
226
function currentApp(): Folder;
227
228
/**
229
* iOS-specific folders
230
*/
231
namespace ios {
232
function library(): Folder;
233
function developer(): Folder;
234
function desktop(): Folder;
235
function downloads(): Folder;
236
function movies(): Folder;
237
function music(): Folder;
238
function pictures(): Folder;
239
}
240
241
/**
242
* Android-specific folders
243
*/
244
namespace android {
245
function externalStorage(): Folder;
246
function externalCacheDir(): Folder;
247
function externalFilesDir(): Folder;
248
}
249
}
250
```
251
252
### Path Utilities
253
254
Path manipulation utilities for cross-platform path handling and normalization.
255
256
```typescript { .api }
257
/**
258
* Path utilities namespace
259
*/
260
namespace path {
261
/**
262
* Path separator for current platform
263
*/
264
const separator: string;
265
266
/**
267
* Normalize path separators for current platform
268
*/
269
function normalize(path: string): string;
270
271
/**
272
* Join path segments with proper separators
273
*/
274
function join(...paths: string[]): string;
275
276
/**
277
* Get directory name from path
278
*/
279
function dirname(path: string): string;
280
281
/**
282
* Get filename from path
283
*/
284
function basename(path: string): string;
285
286
/**
287
* Get file extension from path
288
*/
289
function extname(path: string): string;
290
291
/**
292
* Check if path is absolute
293
*/
294
function isAbsolute(path: string): boolean;
295
296
/**
297
* Resolve relative path to absolute
298
*/
299
function resolve(...paths: string[]): string;
300
}
301
```
302
303
**Path Utilities Usage Examples:**
304
305
```typescript
306
import { path, knownFolders } from "tns-core-modules";
307
308
// Path manipulation
309
const filePath = path.join("documents", "data", "config.json");
310
console.log("Joined path:", filePath);
311
312
const normalized = path.normalize("/documents//data/./config.json");
313
console.log("Normalized:", normalized);
314
315
// Path information
316
const fullPath = "/app/documents/data/config.json";
317
console.log("Directory:", path.dirname(fullPath)); // "/app/documents/data"
318
console.log("Filename:", path.basename(fullPath)); // "config.json"
319
console.log("Extension:", path.extname(fullPath)); // ".json"
320
321
// Platform-specific separators
322
const platformPath = path.join("folder", "subfolder", "file.txt");
323
// Windows: "folder\\subfolder\\file.txt"
324
// Unix/iOS/Android: "folder/subfolder/file.txt"
325
326
// Resolve relative paths
327
const documentsPath = knownFolders.documents().path;
328
const configPath = path.resolve(documentsPath, "config", "app.json");
329
console.log("Resolved path:", configPath);
330
```
331
332
### Advanced File System Operations
333
334
Advanced file system operations for comprehensive file management.
335
336
```typescript { .api }
337
/**
338
* File system utilities for advanced operations
339
*/
340
namespace FileSystem {
341
// File type detection
342
function isTextFile(path: string): boolean;
343
function isBinaryFile(path: string): boolean;
344
345
// File comparison
346
function compareFiles(path1: string, path2: string): Promise<boolean>;
347
function compareFilesSync(path1: string, path2: string): boolean;
348
349
// Directory operations
350
function createDirectory(path: string): Promise<void>;
351
function createDirectorySync(path: string): void;
352
function copyDirectory(source: string, destination: string): Promise<void>;
353
function moveDirectory(source: string, destination: string): Promise<void>;
354
355
// File operations
356
function copyFile(source: string, destination: string): Promise<void>;
357
function moveFile(source: string, destination: string): Promise<void>;
358
359
// Disk space
360
function getAvailableSpace(): Promise<number>;
361
function getTotalSpace(): Promise<number>;
362
}
363
```
364
365
**Complete File System Example:**
366
367
```typescript
368
import { File, Folder, knownFolders, path } from "tns-core-modules";
369
370
class FileManager {
371
private documentsFolder: Folder;
372
373
constructor() {
374
this.documentsFolder = knownFolders.documents();
375
}
376
377
async saveUserData(data: any): Promise<void> {
378
const dataFolder = this.documentsFolder.getFolder("userData");
379
const file = dataFolder.getFile("profile.json");
380
381
await file.writeText(JSON.stringify(data, null, 2));
382
}
383
384
async loadUserData(): Promise<any> {
385
const dataFolder = this.documentsFolder.getFolder("userData");
386
const file = dataFolder.getFile("profile.json");
387
388
if (File.exists(file.path)) {
389
const content = await file.readText();
390
return JSON.parse(content);
391
}
392
return null;
393
}
394
395
async backup(): Promise<void> {
396
const backupFolder = this.documentsFolder.getFolder("backups");
397
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
398
const backupFile = backupFolder.getFile(`backup-${timestamp}.json`);
399
400
const userData = await this.loadUserData();
401
if (userData) {
402
await backupFile.writeText(JSON.stringify(userData));
403
}
404
}
405
406
async listBackups(): Promise<string[]> {
407
const backupFolder = this.documentsFolder.getFolder("backups");
408
const entities = await backupFolder.getEntities();
409
410
return entities
411
.filter(entity => entity instanceof File && entity.name.startsWith("backup-"))
412
.map(file => file.name);
413
}
414
}
415
```