The File System module provides high-level abstractions for file system entities
such as files, folders, known folders, paths, separators, etc.
const fileSystemModule = require("tns-core-modules/file-system");
import { knownFolders, Folder, File } from "tns-core-modules/file-system";
Create folders, files and file content
const documents = fileSystemModule.knownFolders.documents();
const folder = documents.getFolder(vm.get("folderName") || "testFolder");
const file = folder.getFile(`${(vm.get("fileName") || "testFile")}`.txt);
file.writeText(vm.get("fileTextContent") || "some random content")
.then((result) => {
file.readText()
.then((res) => {
vm.set("successMessage", `Successfully saved in${file.path}`);
vm.set("writtenContent", res);
vm.set("isItemVisible", true);
});
}).catch((err) => {
console.log(err);
});
const documents: Folder = <Folder>knownFolders.documents();
const folder: Folder = <Folder>documents.getFolder(vm.get("folderName") || "testFolder");
const file: File = <File>folder.getFile(`${(vm.get("fileName") || "testFile")}` + `.txt`);
file.writeText(vm.get("fileTextContent") || "some random content")
.then(() => {
file.readText()
.then((res) => {
vm.set("successMessage", `Successfully saved in${file.path}`);
vm.set("writtenContent", res);
vm.set("isItemVisible", true);
});
}).catch((err) => {
console.log(err);
});
Removing a File
file.remove()
.then((res) => {
// Success removing the file.
vm.set("resultMessage", "File successfully deleted!");
}).catch((err) => {
console.log(err.stack);
});
file.remove()
.then((res) => {
// Success removing the file.
vm.set("resultMessage", "File successfully deleted!");
}).catch((err) => {
console.log(err.stack);
});
Removing a Folder
// Remove a folder and recursively its content.
myFolder.remove()
.then((fres) => {
// Success removing the folder.
vm.set("resultMessage", "Folder successfully deleted!");
}).catch((err) => {
console.log(err.stack);
});
// Remove a folder and recursively its content.
myFolder.remove()
.then((fres) => {
// Success removing the folder.
vm.set("resultMessage", "Folder successfully deleted!");
}).catch((err) => {
console.log(err.stack);
});
Clearing the Contents of a Folder
myFolder.clear()
.then((res) => {
// Successfully cleared the folder.
vm.set("resultMessage", "Folder successfully cleared!");
}).catch((err) => {
console.log(err.stack);
});
myFolder.clear()
.then((res) => {
// Successfully cleared the folder.
vm.set("resultMessage", "Folder successfully cleared!");
}).catch((err) => {
console.log(err.stack);
});
Normalize a Path
let documentsFolder = fileSystemModule.knownFolders.documents();
const currentAppFolder = fileSystemModule.knownFolders.currentApp();
const tempFolder = fileSystemModule.knownFolders.temp();
const testPath = "///test.txt";
// Get a normalized path such as <folder.path>/test.txt from <folder.path>///test.txt
vm.set("documents", fileSystemModule.path.normalize(documentsFolder.path + testPath));
vm.set("currentApp", fileSystemModule.path.normalize(currentAppFolder.path + testPath));
vm.set("temp", fileSystemModule.path.normalize(tempFolder.path + testPath));
let documentsFolder: Folder = <Folder>knownFolders.documents();
const currentAppFolder = knownFolders.currentApp();
const tempFolder = knownFolders.temp();
const testPath: string = "///test.txt";
// Get a normalized path such as <folder.path>/test.txt from <folder.path>///test.txt
vm.set("documents", path.normalize(documentsFolder.path + testPath));
vm.set("currentApp", path.normalize(currentAppFolder.path + testPath));
vm.set("temp", path.normalize(tempFolder.path + testPath));
Path Join
// Generate a path like <documents.path>/myFiles/test.txt
documentsFolder = fileSystemModule.knownFolders.documents();
const filePath = fileSystemModule.path.join(documentsFolder.path, "myFiles", "test.txt");
// Generate a path like <documents.path>/myFiles/test.txt
documentsFolder = <Folder>knownFolders.documents();
const filePath: string = path.join(documentsFolder.path, "myFiles", "test.txt");
Get the Path Separator
// An OS dependent path separator, "\" or "/".
const separator = fileSystemModule.path.separator;
// An OS dependent path separator, "\" or "/".
const separator = path.separator;
Get or Create a File With Path
const documentsFolder = fileSystemModule.knownFolders.documents();
const path = fileSystemModule.path.join(documentsFolder.path, "FileFromPath.txt");
const file = fileSystemModule.File.fromPath(path);
// Writing text to the file.
file.writeText(vm.get("textContentToBeSaved"))
.then((result) => {
// Succeeded writing to the file.
file.readText().then((res) => {
// Succeeded read from file.
vm.set("isContentSaved", true);
vm.set("savedContent", res);
console.log(`File content: ${res}`);
});
}).catch((err) => {
console.log(err.stack);
});
const documentsFolder: Folder = <Folder>knownFolders.documents();
const filePath: string = path.join(documentsFolder.path, "FileFromPath.txt");
const file: File = File.fromPath(filePath);
// Writing text to the file.
file.writeText(vm.get("textContentToBeSaved"))
.then((result) => {
// Succeeded writing to the file.
file.readText().then((res) => {
// Succeeded read from file.
vm.set("isContentSaved", true);
vm.set("savedContent", res);
console.log(`File content: ${res}`);
});
}).catch((err) => {
console.log(err.stack);
});
Get or Create a Folder With Path
const folderPath = fileSystemModule.path.join(fileSystemModule.knownFolders.documents().path, "music");
const folder = fileSystemModule.Folder.fromPath(folderPath);
const folderPath: string = path.join(knownFolders.documents().path, "music");
const folder: Folder = <Folder>Folder.fromPath(folderPath);
Reading from a File
file.readText()
.then((res) => {
vm.set("writtenContent", res);
}).catch((err) => {
console.log(err.stack);
});
file.readText()
.then((res) => {
vm.set("writtenContent", res);
}).catch((err) => {
console.log(err.stack);
});
Reading binary data from a File
const image = imageSourceModule.fromResource("icon");
const folder = fileSystemModule.knownFolders.documents();
const path = fileSystemModule.path.join(folder.path, "Test.png");
const saved = image.saveToFile(path, "png");
if (saved) {
const imageFile = fileSystemModule.File.fromPath(path);
const binarySource = imageFile.readSync((err) => {
console.log(err);
});
console.log(this.binarySource);
const image: ImageSource = fromResource("icon");
const folder: Folder = knownFolders.documents();
const filePath: string = path.join(folder.path, "Test.png");
const saved = image.saveToFile(filePath, "png");
if (saved) {
const imageFile: File = File.fromPath(filePath);
const binarySource = imageFile.readSync((err) => {
console.log(err);
});
console.log(this.binarySource);
Writing binary data to a File
imageFile.writeSync(binarySource, (err) => {
console.log(err);
});
imageFile.writeSync(binarySource, (err) => {
console.log(err);
});
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.
documents = fileSystemModule.knownFolders.documents();
documents.getEntities()
.then((entities) => {
// entities is array with the document's files and folders.
entities.forEach((entity) => {
array.push(
{
name: entity.name,
path: entity.path,
lastModified: entity.lastModified.toString()
}
);
});
}).catch((err) => {
// Failed to obtain folder's contents.
console.log(err.stack);
});
documents = knownFolders.documents();
documents.getEntities()
.then((entities) => {
// entities is array with the document's files and folders.
entities.forEach((entity) => {
array.push(
{
name: entity.name,
path: entity.path,
lastModified: entity.lastModified.toString()
}
);
});
}).catch((err) => {
// Failed to obtain folder's contents.
console.log(err.stack);
});
Checking if a File Exists
documents = fileSystemModule.knownFolders.documents();
const path = fileSystemModule.path.join(documents.path, "Text.txt");
const exists = fileSystemModule.File.exists(path);
console.log(`Does Text.txt exists: ${exists}`);
documents = knownFolders.documents();
const filePath = path.join(documents.path, "Text.txt");
const exists = File.exists(filePath);
console.log(`Does Text.txt exists: ${exists}`);
Checking if a Folder Exists
const temp = fileSystemModule.knownFolders.temp();
const tempExists = fileSystemModule.Folder.exists(temp.path);
console.log(`Does temp folder exists: ${tempExists}`);
const temp: Folder = <Folder>knownFolders.temp();
const tempExists: boolean = Folder.exists(temp.path);
console.log(`Does temp folder exists: ${tempExists}`);
Renaming a File
const fileName = vm.get("fileName");
file.rename(`${fileName}.txt`)
.then((res) => {
// File Successfully Renamed.
vm.set("fileSuccessMessage", `File renamed to: ${fileName}.txt`);
vm.set("isItemVisible", true);
}).catch((err) => {
// Error!
console.log("Error: ");
console.log(err);
dialogs.alert(err)
.then(() => {
console.log("Dialog closed!");
});
});
const fileName: string = vm.get("fileName");
file.rename(`${fileName}.txt`)
.then(() => {
// File Successfully Renamed.
vm.set("fileSuccessMessage", `File renamed to: ${fileName}.txt`);
vm.set("isItemVisible", true);
}).catch((err) => {
// Error!
console.log("Error: ");
console.log(err);
dialogs.alert(err)
.then(() => {
console.log("Dialog closed!");
});
});
Renaming a Folder
const folderName = vm.get("folderName");
myFolder.rename(folderName)
.then((res) => {
// Folder Successfully Renamed.
vm.set("folderSuccessMessage", `Folder renamed to: ${folderName}`);
vm.set("isFolderItemVisible", true);
}).catch((err) => {
// Error!
console.log("Error: ");
console.log(err);
dialogs.alert(err)
.then(() => {
console.log("Dialog closed!");
});
});
const folderName: string = vm.get("folderName");
myFolder.rename(folderName)
.then(() => {
// Folder Successfully Renamed.
vm.set("folderSuccessMessage", `Folder renamed to: ${folderName}`);
vm.set("isFolderItemVisible", true);
}).catch((err) => {
// Error!
console.log("Error: ");
console.log(err);
dialogs.alert(err)
.then(() => {
console.log("Dialog closed!");
});
});
Improve this document
Demo Source
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 "//". |