FileSystem
The FileSystem module provides high-level abstractions for file system entities such as files, folders, known folders, paths, separators, etc.
Usage
Import
import { File, Folder, knownFolders, path } from '@nativescript/core'
import { File, Folder, knownFolders, path } from '@nativescript/core'
Create a File
const documents = 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('message', 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 = 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)
})
Remove 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: boolean) => {
// Success removing the file.
vm.set('resultMessage', 'File successfully deleted!')
})
.catch(err => {
console.log(err.stack)
})
Removing a Folder
folder
.remove()
.then(res => {
// Success removing the folder.
vm.set('resultMessage', 'Folder successfully deleted!')
})
.catch(err => {
console.log(err.stack)
})
folder
.remove()
.then((res: boolean) => {
// Success removing the folder.
vm.set('resultMessage', 'Folder successfully deleted!')
})
.catch(err => {
console.log(err.stack)
})
Clearing the contents of a Folder
folder
.clear()
.then(res => {
// Successfully cleared the folder.
vm.set('resultMessage', 'Folder successfully cleared!')
})
.catch(err => {
console.log(err.stack)
})
folder
.clear()
.then((res: boolean) => {
// Successfully cleared the folder.
vm.set('resultMessage', 'Folder successfully cleared!')
})
.catch(err => {
console.log(err.stack)
})
Get or create a File with Path
const documentsFolder = knownFolders.documents()
const filePath = path.join(documentsFolder.path, 'FileFromPath.txt')
const file = File.fromPath(filePath)
// Writing text to the file.
file
.writeText('Some text')
.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 = knownFolders.documents()
const filePath = path.join(documentsFolder.path, 'FileFromPath.txt')
const file = File.fromPath(filePath)
// Writing text to the file.
file
.writeText('Some text')
.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)
})
Reading binary data from a File
import { ImageSource } from '@nativescript/core'
const folder = knownFolders.documents()
const fPath = path.join(folder.path, 'Test.png')
const imageFile = File.fromPath(fPath)
const image = ImageSource.fromResource('icon')
.then(image => {
const saved = image.saveToFile(fPath, 'png')
if (saved) {
Dialogs.alert('Saved')
const binarySource = imageFile.readSync(err => {
console.log(err)
})
console.log(binarySource)
}
})
.catch(err => Dialogs.alert(err))
import { ImageSource } from '@nativescript/core'
const folder = knownFolders.documents()
const fPath = path.join(folder.path, 'Test.png')
const imageFile = File.fromPath(fPath)
const image = ImageSource.fromResource('icon')
.then((image: ImageSource) => {
const saved = image.saveToFile(fPath, 'png')
if (saved) {
Dialogs.alert('Saved')
const binarySource = imageFile.readSync(err => {
console.log(err)
})
console.log(binarySource)
}
})
.catch(err => Dialogs.alert(err))
Checking if a File Exists
const documents = knownFolders.documents()
const path = path.join(documents.path, 'Text.txt')
const exists = File.exists(path)
console.log(`Does Text.txt exists: ${exists}`)
const documents = knownFolders.documents()
const fPath = path.join(documents.path, 'Text.txt')
const exists = File.exists(fPath)
console.log(`Does Text.txt exists: ${exists}`)
Renaming a File
const newName = 'NewName'
const documents = knownFolders.documents()
const file = documents.getFile('Text.txt')
const fPath = path.join(documents.path, 'Text.txt')
file
.rename(`${newName}.txt`)
.then(res => {
// File Successfully Renamed.
Dialogs.alert(`File renamed to: ${newName}.txt`)
vm.set('fileSuccessMessage', `File renamed to: ${newName}.txt`)
vm.set('isItemVisible', true)
})
.catch(err => {
// Error!
console.log('Error: ')
console.log(err)
Dialogs.alert(err).then(() => {
console.log('Dialog closed!')
})
})
const newName = 'NewName'
const documents = knownFolders.documents()
const file = documents.getFile('Text.txt')
const fPath = path.join(documents.path, 'Text.txt')
file
.rename(`${newName}.txt`)
.then(res => {
// File Successfully Renamed.
Dialogs.alert(`File renamed to: ${newName}.txt`)
vm.set('fileSuccessMessage', `File renamed to: ${newName}.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 newName = 'newName'
folder
.rename(newName)
.then(res => {
// Folder Successfully Renamed.
Dialogs.alert(`Folder renamed to: ${newName} ${res}`)
vm.set('folderSuccessMessage', `Folder renamed to: ${newName}`)
vm.set('isFolderItemVisible', true)
})
.catch(err => {
// Error!
console.log('Error: ')
console.error(err)
})
const newName = 'newName'
folder
.rename(newName)
.then((res: boolean) => {
// Folder Successfully Renamed.
Dialogs.alert(`Folder renamed to: ${newName} ${res}`)
vm.set('folderSuccessMessage', `Folder renamed to: ${newName}`)
vm.set('isFolderItemVisible', true)
})
.catch(err => {
// Error!
console.log('Error: ')
console.error(err)
})
Getting Folder Contents
Getting all folder entities in an array may be slow with a large number of files. Enumerating the folder entities would iterate the files one by one without blocking the UI.
folder
.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()
})
console.log(array.length)
})
})
.catch(err => {
// Failed to obtain folder's contents.
console.log(err.stack)
})
folder
.getEntities()
.then((entities: FileSystemEntity[]) => {
// 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()
})
console.log(array.length)
})
})
.catch(err => {
// Failed to obtain folder's contents.
console.log(err.stack)
})
Removing a Folder
folder
.remove()
.then(res => {
// Success removing the folder.
vm.set('resultMessage', 'Folder successfully deleted!')
Dialogs.alert(res)
})
.catch(err => {
console.log(err.stack)
})
folder
.remove()
.then((res: boolean) => {
// Success removing the folder.
vm.set('resultMessage', 'Folder successfully deleted!')
Dialogs.alert(res)
})
.catch(err => {
console.log(err.stack)
})
Checking if a Folder Exists
const documents = knownFolders.documents()
const folder = documents.getFolder(vm.get('folderName') || 'testFolder')
const folderExists = Folder.exists(folder.path)
console.log(folderExists) // true
const folder2Path = path.join(documents.path, 'myFolder')
const folder2Exists = Folder.exists(folder2Path)
console.log(folder2Exists) // false
const documents = knownFolders.documents()
const folder: Folder = documents.getFolder(vm.get('folderName') || 'testFolder')
const folderExists: boolean = Folder.exists(folder.path)
console.log(folderExists) // true
const folder2Path: string = path.join(documents.path, 'myFolder')
const folder2Exists: boolean = Folder.exists(folder2Path)
console.log(folder2Exists) // false
Normalize a Path
let documentsFolder = knownFolders.documents()
const currentAppFolder = knownFolders.currentApp()
const tempFolder = knownFolders.temp()
const testPath = '///test.txt'
// Get a normalized path such as <folder.path>/test.txt from <folder.path>///test.txt
console.log('documents', path.normalize(documentsFolder.path + testPath))
console.log('currentApp', path.normalize(currentAppFolder.path + testPath))
console.log('temp', path.normalize(tempFolder.path + testPath))
let documentsFolder = knownFolders.documents()
const currentAppFolder = knownFolders.currentApp()
const tempFolder = knownFolders.temp()
const testPath = '///test.txt'
// Get a normalized path such as <folder.path>/test.txt from <folder.path>///test.txt
console.log('documents', path.normalize(documentsFolder.path + testPath))
console.log('currentApp', path.normalize(currentAppFolder.path + testPath))
console.log('temp', path.normalize(tempFolder.path + testPath))
Path join
// Generate a path like <documents.path>/myFiles/test.txt
const documentsFolder = knownFolders.documents()
const filePath = path.join(documentsFolder.path, 'myFiles', 'test.txt')
// Generate a path like <documents.path>/myFiles/test.txt
const documentsFolder = <Folder>knownFolders.documents()
const filePath: string = path.join(documentsFolder.path, 'myFiles', 'test.txt')
File Properties
Name | Type | Description |
---|---|---|
|
|
Gets the extension of the file.property. |
|
|
Gets a value indicating whether the file is currently locked, meaning a background operation associated with this file is running.property. |
|
|
Gets the Date object specifying the last time this entity was modified. |
|
|
Gets the name of the entity. |
|
|
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. |
|
|
Gets the fully-qualified path (including the extension for a File) of the entity. |
|
|
Gets the known name of this instance. Defined only if it has been constructed from a known color name - e.g. "red". This is a read-only property. |
|
|
Gets the size in bytes of the file. |
File Methods
Name | Return Type | Description |
---|---|---|
|
|
Reads the binary content of the file asynchronously. |
|
|
Reads the binary content of the file synchronously. |
|
|
Reads the content of the file asynchronously as a string using the specified encoding (defaults to UTF-8). |
|
|
Reads the content of the file as a string synchronously, using the specified encoding (defaults to UTF-8). |
|
|
Removes (deletes) the current file asynchronously from the file system. |
|
|
Removes (deletes) the current file from the file system synchronously. |
|
|
Renames the current file asynchronously using the specified name. |
|
|
Renames the current file synchronously using the specified name. |
|
|
Writes the provided binary content, asynchronously, to the file. |
|
|
Asynchronously writes the content of the file as a string using the specified encoding (defaults to UTF-8). |
|
|
Writes the content of the file as a string synchronously using the specified encoding (defaults to UTF-8). |
|
|
Checks whether a File with the specified path already exists. |
|
|
Gets or creates a File entity at the specified path. |
Folder Properties
Name | Type | Description |
---|---|---|
|
|
Determines whether this instance is a KnownFolder (accessed through the KnownFolders object). |
|
|
Gets the Date object specifying the last time this entity was modified. |
|
|
Gets the name of the entity. |
|
|
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. |
|
|
Gets the fully-qualified path (including the extension for a File) of the entity. |
Folder Methods
Name | Return Type | Description |
---|---|---|
|
|
Deletes all the files and folders (recursively), contained within this Folder. |
|
|
Deletes all the files and folders (recursively), contained within this Folder synchronously. |
|
|
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. |
|
|
Enumerates all the top-level FileSystem entities residing within this folder. |
|
|
Gets all the top-level entities residing within this folder. |
|
|
Gets all the top-level entities residing within this folder synchronously |
|
|
Gets or creates a File entity with the specified name within this Folder. |
|
|
Gets or creates a Folder entity with the specified name within this Folder. |
|
|
Removes (deletes) the current Entity from the file system. |
|
|
Removes (deletes) the current Entity from the file system synchronously. |
knownFolders Methods
Name | Return Type | Description |
---|---|---|
|
|
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. |
|
|
Gets the Documents folder available for the current application. This Folder is private for the application and not accessible from Users/External apps. |
|
|
Gets the Temporary (Caches) folder available for the current application. This Folder is private for the application and not accessible from Users/External apps. |
path Methods
Name | Return Type | Description |
---|---|---|
|
|
Joins all the provided string components, forming a valid and normalized path. |
|
|
Normalizes a path, taking care of occurrances like ".." and "//". |