The File System module provides high-level abstractions for file
system entities such as files, folders, known folders, paths,
separators, etc.
import { knownFolders, path, File, Folder } from "tns-core-modules/file-system";
Create folders, files and file content
let documents = knownFolders.documents();
this.folder = documents.getFolder(this.folderName || "testFolder");
this.file = this.folder.getFile((this.fileName || "testFile") + ".txt");
this.file.writeText(this.fileTextContent || "some random content")
.then(result => {
this.file.readText()
.then(res => {
this.successMessage = "Successfully saved in " + this.file.path;
this.writtenContent = res;
this.isItemVisible = true;
});
}).catch(err => {
console.log(err);
});
Removing a File
this.file.remove()
.then(res => {
// Success removing the file.
this.resultMessage = "File successfully deleted!";
}).catch(err => {
console.log(err.stack);
});
Normalize a Path
let documentsFolder = knownFolders.documents();
let currentAppFolder = knownFolders.currentApp();
let tempFolder = knownFolders.temp();
let testPath = "///test.txt";
// Get a normalized path such as <folder.path>/test.txt from <folder.path>///test.txt
this.documents = path.normalize(documentsFolder.path + testPath);
this.currentApp = path.normalize(currentAppFolder.path + testPath);
this.temp = path.normalize(tempFolder.path + testPath);
Path Join
// Generate a path like <documents.path>/myFiles/test.txt
documentsFolder = knownFolders.documents();
let filePath = path.join(documentsFolder.path, "myFiles", "test.txt");
Get the Path Separator
// An OS dependent path separator, "\" or "/".
let separator = path.separator;
Get or Create a File With Path
let documentsFolder = knownFolders.documents();
let myPath = path.join(documentsFolder.path, "FileFromPath.txt");
let file = File.fromPath(myPath);
// Writing text to the file.
file.writeText(this.textContentToBeSaved)
.then(result => {
// Succeeded writing to the file.
file.readText().then(res => {
// Succeeded read from file.
this.isContentSaved = true;
this.savedContent = res;
console.log("File content: " + res);
});
}).catch(err => {
console.log(err.stack);
});
Reading from a File
this.file.readText()
.then(res => {
this.writtenContent = res;
}).catch(err => {
console.log(err.stack);
});
Reading binary data from a File
let image = imageSource.fromResource("icon");
let folder = knownFolders.documents();
let myPath = path.join(folder.path, "Test.png");
let saved = image.saveToFile(myPath, "png");
if (saved) {
this.imageFile = File.fromPath(myPath);
this.binarySource = this.imageFile.readSync(err => { console.log("Error:" + err); });
console.log(this.binarySource);
Writing binary data to a File
this.imageFile.writeSync(this.binarySource, err => {
console.log(err);
});
Checking if a File Exists
this.documents = knownFolders.documents();
let myPath = path.join(this.documents.path, "Text.txt");
let exists = File.exists(myPath);
console.log("Does Text.txt exists: " + exists);
Renaming a File
this.file.rename(this.fileName + ".txt")
.then(res => {
// File Successfully Renamed.
this.fileSuccessMessage = "File renamed to: " + this.fileName + ".txt";
this.isItemVisible = true;
}).catch(err => {
// Error!
});
Create folders, files and file content
let documents = knownFolders.documents();
this.folder = documents.getFolder(this.folderName || "testFolder");
this.file = this.folder.getFile((this.fileName || "testFile") + ".txt");
this.file.writeText(this.fileTextContent || "some random content")
.then(result => {
this.file.readText()
.then(res => {
this.successMessage = "Successfully saved in " + this.file.path;
this.writtenContent = res;
this.isItemVisible = true;
});
}).catch(err => {
console.log(err);
});
Removing a Folder
// Remove a folder and recursively its content.
this.myFolder.remove()
.then(fres => {
// Success removing the folder.
this.resultMessage = "Folder successfully deleted!";
}).catch(err => {
console.log(err.stack);
});
Clearing the Contents of a Folder
this.myFolder.clear()
.then(res => {
// Successfully cleared the folder.
this.resultMessage = "Folder successfully cleared!";
}).catch(err => {
console.log(err.stack);
});
Get or Create a Folder With Path
let folderPath = path.join(knownFolders.documents().path, "music");
let folder = Folder.fromPath(folderPath);
Getting Folder Contents
Getting all folder entities in array may be slow with large
number of files. Enumerating the folder entities would iterate
the files one by one without blocking the UI.
this.documents = knownFolders.documents();
this.documents.getEntities()
.then(entities => {
// entities is array with the document's files and folders.
entities.forEach(entity => {
// console.log(entity.name);
// console.log(entity.path);
// console.log(entity.lastModified);
this.folderEntities.push(
new FolderEntity(entity.name, entity.path, entity.lastModified.toString())
);
});
}).catch(err => {
// Failed to obtain folder's contents.
console.log(err.stack);
});
Checking if a Folder Exists
let temp = knownFolders.temp();
let tempExists = Folder.exists(temp.path);
console.log("Does temp folder exists: " + tempExists);
Renaming a Folder
this.myFolder.rename(this.folderName)
.then(res => {
// Folder Successfully Renamed.
this.folderSuccessMessage = "Folder renamed to: " + this.folderName;
this.isFolderItemVisible = true;
}).catch(err => {
// Error!
});
Name |
Type |
Description |
extension |
string |
Gets the extension of the file. |
isLocked |
boolean |
Gets a value indicating whether the file is currently
locked, meaning a background operation associated with
this file is running.
|
lastModified |
Date |
Gets the Date object specifying the last time this entity
was modified.
|
name |
string |
Gets the name of the entity. |
parent |
Folder |
Gets the Folder object representing the parent of this
entity. Will be null for a root folder like Documents or
Temporary. This property is readonly.
|
path |
string |
Gets the fully-qualified path (including the extension for
a File) of the entity.
|
size |
number |
Gets the size in bytes of the file. |
Name |
Return Type |
Description |
read |
Promise<any> |
Reads the binary content of the file asynchronously.
|
readSync(onError?: function) |
any |
Reads the binary content of the file synchronously. |
readText(encoding?: string) |
Promise<string> |
Reads the content of the file as a string using the
specified encoding (defaults to UTF-8).
|
readTextSync(onError?: function, encoding?:
string)
|
string |
Reads the content of the file as a string synchronously,
using the specified encoding (defaults to UTF-8).
|
remove |
void |
Removes (deletes) the current Entity from the file system.
|
removeSync(onError?: function) |
void |
Removes (deletes) the current Entity from the file system
synchronously.
|
rename(newName: string) |
Promise<any> |
Renames the current entity using the specified name.
|
renameSync(newName: string, onError?: function)
|
void |
Renames the current entity synchronously, using the
specified name.
|
write(newName: string) |
Promise<void> |
Writes the provided binary content to the file. |
writeSync(newName: string, onError?: function)
|
void |
Writes the provided binary content to the file
synchronously.
|
writeText(encoding?: string) |
Promise<string> |
Writes the content of the file as a string using the
specified encoding (defaults to UTF-8).
|
writeTextSync(onError?: function, encoding?:
string)
|
string |
Writes the content of the file as a string synchronously,
using the specified encoding (defaults to UTF-8).
|
exists(path: string) |
boolean |
Checks whether a File with the specified path already
exists.
|
fromPath(path: string) |
File |
Gets or creates a File entity at the specified path.
|
Name |
Type |
Description |
isKnown |
boolean |
Determines whether this instance is a KnownFolder
(accessed through the KnownFolders object).
|
lastModified |
Date |
Gets the Date object specifying the last time this entity
was modified.
|
name |
string |
Gets the name of the entity. |
parent |
Folder |
Gets the Folder object representing the parent of this
entity. Will be null for a root folder like Documents or
Temporary. This property is readonly.
|
path |
string |
Gets the fully-qualified path (including the extension for
a File) of the entity.
|
Name |
Return Type |
Description |
clear |
Promise<any> |
Deletes all the files and folders (recursively), contained
within this Folder.
|
clearSync(onError?: function) |
void |
Deletes all the files and folders (recursively), contained
within this Folder synchronously.
|
contains(name: string) |
boolean |
Checks whether this Folder contains an Entity with the
specified name. The path of the folder is added to the
name to resolve the complete path to check for.
|
eachEntity(onEntity: function) |
any |
Enumerates all the top-level FileSystem entities residing
within this folder.
|
getEntities |
Promise<Array<FileSystemEntity>>
|
Gets all the top-level entities residing within this
folder.
|
getEntitiesSync(onError?: function) |
Array<FileSystemEntity> |
Gets all the top-level entities residing within this
folder synchronously
|
getFile(name: string) |
File |
Gets or creates a File entity with the specified name
within this Folder.
|
getFolder(name: string) |
Folder |
Gets or creates a Folder entity with the specified name
within this Folder.
|
remove |
Promise<any> |
Removes (deletes) the current Entity from the file system.
|
removeSync |
removeSync(onError?: function) |
Removes (deletes) the current Entity from the file system
synchronously.
|
Name |
Return Type |
Description |
currentApp |
Folder |
Gets the root folder for the current application. This
Folder is private for the application and not accessible
from Users/External apps. iOS - this folder is read-only
and contains the app and all its resources.
|
documents |
Folder |
Gets the Documents folder available for the current
application. This Folder is private for the application
and not accessible from Users/External apps.
|
temp |
Folder |
Gets the Temporary (Caches) folder available for the
current application. This Folder is private for the
application and not accessible from Users/External apps.
|
Name |
Return Type |
Description |
join(...paths: string[]) |
string |
Joins all the provided string components, forming a valid
and normalized path.
|
normalize(path: string) |
string |
Normalizes a path, taking care of occurrances like ".."
and "//".
|