Fundamental Concepts
FileSystem
Work with the device file system
File system handing with @nativescript/core provides easy-to-use APIs for working with files and folders in a device's file system like managing files, folders, paths, and separators, etc.
How to work with files and folders β
Accessing the Documents folder β
To get the root Documents folder, call the documents()
method on knownFolders
:
import { knownFolders } from'@nativescript/core'
constdocuments= knownFolders.documents()
Accessing the temporary(Caches) folder β
import { knownFolders } from'@nativescript/core'
constcache= knownFolders.temp()
Accessing the root folder for the app β
import { knownFolders } from'@nativescript/core'
constappRootFolder= knownFolders.currentApp()
Creating a folder β
To create a folder, call the getFolder()
method on an instance of Folder
(any of the root folders above or one you create) and pass it the name of the folder.
folder.getFolder('folder-name')
You can also use the fromPath static method of the Folder class.
constfolderPath= path.join(knownFolders.documents().path, 'music')
constfolder:Folder= Folder.fromPath(folderPath)
Renaming a folder β
To rename a folder, use the rename
or renameSync
method:
folder
.rename(newName)
.then((res) => {
// Folder Successfully renamed.
})
.catch((err) => {
//Folder couldn't be renamed
console.error(err)
})
Check if a folder exists β
constfolderExists:boolean= Folder.exists('folder-path')
Accessing a folder's content β
To get a folder's files and folders, use the getEntitiesSync
or getEntities
method:
folder
.getEntities()
.then((entities:FileSystemEntity[]) => {
// do something
})
.catch((err) => {
console.log(err)
})
Deleting the contents of a Folder β
To delete all the content of a Folder, use the clear or clearSync method of a Folder instance:
folder
.clear()
.then((result) => {
// successful delete
})
.catch((rerror) => {})
// OR
folder.clearSync((error) => {})
Deleting a folder β
To delete a folder, use the remove
or removeSync
method:
folder
.remove()
.then((value:boolean) => {
console.log(value)
})
.catch((error) => {
console.error(error.message)
})
Creating, writing to and reading from a text file β
- To create a file, call the
getFile()
method on an instance of theFolder
class and pass it the file name with the extension.
folder.getFile('my-text.txt')
//or
constfilePath= path.join(folder.path, 'my-text.txt')
constfile= File.fromPath(filePath)
- To save a text to a file, use the
writeText
orwriteTextSync
method:
file
.writeText('Some text')
.then((result) => {
// Succeeded writing to the file.
})
.catch((error) => {
console.log(error)
})
- To extract data from a text file, you can use the readText or readTextSync method of the file instance. Here's an example of how to use it:
file
.readText()
.then((res) => {
// Succeeded read from file.
})
.catch((error) => {})
Check if a file exists β
To check if a file exists, you can use exists with the file path:
constexists= File.exists(filePath)
Renaming a file β
To rename a file, use the rename
or renameSync
method:
file
.rename('new-name.ext')
.then((value) => {})
.catch((err) => {})
Saving a binary data to a file β
To save binary data to a file, use either the write
or writeSync
method:
file
.write(binary data)
.then(result=> {
// Succeeded writing to the file.
})
.catch(error=> {
console.log(error)
})
Reading a binary data from a file β
To read binary data, use the read
or readSync
method of the File instance. For example, you can save an image on the device and retrive it as follows:
async readAnImage() {
constfolder= knownFolders.documents()
constfilePath= path.join(folder.path, 'cat.png')
constimageFile= File.fromPath(filePath)
try {
constimageSource=await ImageSource.fromFile('~/assets/images/download.jpeg')
constsaved:boolean= imageSource.saveToFile(filePath, "png")
if (saved) {
// READ BINARY DATA
constimageBinary=await imageFile.read()
constimg=await ImageSource.fromData(imageBinary)
}
} catch (err) {
}
}
Deleting a file β
To remove a file, use the remove or removeSync method of the File instance:
file
.remove()
.then((res:boolean) => {
// Success removing the file.
})
.catch((err) => {})
Normalizing a path β
To normalize a path use the normalize
or create the path with the join
method from the path object:
consttestPath='///test.txt'
let documentsFolder = knownFolders.documents()
path.normalize(documentsFolder.path + testPath)
FileSystem API β
documents() β
constfolder:Folder= knownFolders.documents()
Gets the Documents folder available for the current application. This Folder is private for the application and not accessible from Users/External apps.
externalDocuments() β
constfolder:Folder= knownFolders.externalDocuments()
Gets the Documents folder available for the current application from an external storage source. This folder has private access, with availability limited to the application, meaning it is not accessible to outside users, bots or external apps.
- On Android, for such read or write access, the flags
READ_EXTERNAL_STORAGE/WRITE_EXTERNAL_STORAGE
permissions need to be set to true. This can be done by adding the following XML code to theAndroidManifest.xml
file:
<uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- There is no external storage on iOS, it is the same as documents().
temp() β
constfolder:Folder= knownFolders.temp()
Gets the Temporary (Caches) folder available for the current application. This Folder is private for the application and not accessible from Users/External apps.
currentApp() β
constfolder:Folder= knownFolders.currentApp()
Gets the root folder for the current application.
iOS known folders β
The following methods allow to access to iOS known folders.
library() β
constfolder:Folder= knownFolders.ios.library()
Gets the NSLibraryDirectory.
developer() β
constfolder:Folder= knownFolders.ios.developer()
Gets the NSDeveloperDirectory.
desktop() β
constfolder:Folder= knownFolders.ios.desktop()
Gets the NSDesktopDirectory.
downloads() β
constfolder:Folder= knownFolders.ios.downloads()
Gets the NSDownloadsDirectory.
movies() β
constfolder:Folder= knownFolders.ios.movies()
Gets the NSMoviesDirectory.
music() β
constfolder:Folder= knownFolders.ios.music()
Gets the NSMusicDirectory.
pictures() β
constfolder:Folder= knownFolders.ios.pictures()
Gets the NSPicturesDirectory.
sharedPublic() β
constfolder:Folder= knownFolders.ios.sharedPublic()
Gets the NSSharedPublicDirectory.
fromPath() β
constfile:File= File.fromPath(path)
or
constfolder:Folder= Folder.fromPath(path)
Gets or creates a Folder or File entity at the specified path.
getFolder β
constfolder:Folder= folder.getFolder(name)
Gets or creates a Folder entity with the specified name
within a Folder.
exists β
constfolderExists:boolean= Folder.exists(path)
or
constfile:boolean= File.exists(path)
Checks whether a Folder or File with the specified path already exists.
isKnown β
constisItAKnownFolder:boolean= folder.isKnown
Determines whether this instance is a known folder (accessed through the knownFolders
object).
Both the File and Folder classes extend the FileSystemEntity which has the following API:
lastModified β
constlastModified:Date= entity.lastModified
Gets the Date object specifying the last time this entity was modified.
name β
constname:string= entity.name
Gets the name of the entity.
path β
constpath:string= entity.path
Gets the fully-qualified path (including the extension for a File) of the entity.
parent β
constparent:Folder= entity.parent
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.
remove() β
constresult=await entity.remove()
Asynchronously removes (deletes) the current Entity from the file system.
removeSync() β
entity.removeSync(onError?: (error:any) => any): void
Removes (deletes) the current Entity from the file system.
rename() β
entity.rename(newName: string): Promise<any>
Asynchronously renames the current entity using the specified name.
renameSync() β
entity.renameSync(newName: string, onError?: (error:any) => any)
Renames the current entity synchronously, using the specified name.
getEntities() β
folder.getEntities(): Promise<Array<FileSystemEntity>>
Asynchronously gets all the top-level entities residing within a folder.
getEntitiesSync() β
folder.getEntitiesSync(onError?: (error:any) => any): Array<FileSystemEntity>
Gets all the top-level entities residing within this folder synchronously. onError
is a optional function to be called if some error occurs.
eachEntity() β
folder.eachEntity(onEntity: (entity:FileSystemEntity) => boolean)
Enumerates all the top-level FileSystem entities within a folder. onEntity
is a callback that receives the current entity.
getFile() β
folder.getFile(name: string): File
Gets or creates a File entity with the specified name within this Folder
extension β
constfileExt:string= file.extension
Gets the extension of the file.
size β
constfileSize:number= file.size
Gets the extension of the file.
isLocked β
constisFileLocked:boolean= file.isLocked
Gets a boolean value indicating whether the file is currently locked, meaning a background operation associated with this file is running.
readText() β
consttext=await file.readText(encoding)
Asynchronously reads the content of the file as a string using an optional encoding value. If you do not pass any encoding, UTF-8
is used.
readTextSync() β
file.readTextSync(onError?: (error:any) => any, encoding?: string): string
Reads the content of the file as a string synchronously, using the specified encoding (defaults to UTF-8). onError
is a function to be called if some IO-error occurs.
read β
constfileContent=await file.read()
Reads the binary content of the file asynchronously.
readSync() β
constfileContent= file.readSync(onError)
Reads the binary content of the file synchronously. onError
is a function to be called if some IO-error occurs.
Parameter | Type | Description |
---|---|---|
onError? | (error: any) => any | An optional function to be called if some IO-error occurs. |
writeText() β
constresult=await file.writeText(content, encoding)
Asynchronously writes the content of the file as a string using the specified encoding (defaults to UTF-8).
Parameter | Type | Description |
---|---|---|
content | string | The content to write. |
encoding? | string | An optional encoding value. If you do not pass any encoding, UTF-8 is used. |
writeTextSync() β
file.writeTextSync(content, onError, encoding): void
Synchronously writes the content of the file as a string using the specified encoding (defaults to UTF-8).
Parameter | Type | Description |
---|---|---|
content | string | The content to write. |
onError? | (error: any) => any | An optional function to be called if some IO-error occurs. |
encoding? | string | An optional encoding value. If you do not pass any encoding, UTF-8 is used. |
write() β
await file.write(content)
Writes the provided binary content to the file asynchronously.
Parameter | Type | Description |
---|---|---|
content | any | The content to write. |
writeSync() β
file.writeSync(content: any, onError?: (error:any) => any): void
Writes the provided binary content to the file synchronously.
Parameter | Type | Description |
---|---|---|
content | any | The content to write. |
onError? | (error: any) => any | An optional function to be called if some IO-error occurs. |
contains() β
constcontainsEntity:boolean= folder.contains(name)
Checks whether this Folder contains an Entity with the specified name.
Parameter | Type | Description |
---|---|---|
name | string | The name of the entity to check for. |
clear() β
constresult=await folder.clear()
Asynchronously deletes all the files and folders (recursively), contained within the Folder.
clearSync() β
folder.clearSync(onError)
Synchronously deletes all the files and folders (recursively), contained within the Folder.
Parameter | Type | Description |
---|---|---|
onError? | (error: any) => any | An optional function to be called if some IO-error occurs. |
path operations β
normalize β
constnormalizedPath:string= path.normalize(path)
Normalizes a path, taking care of occurrences like ..
and //
.
Parameter | Type | Description |
---|---|---|
path | string | The path to normalize. |
join() β
constjoinedPath:string= path.join(...paths)
Joins all the provided string components, forming a valid and normalized path.
Parameter | Type | Description |
---|---|---|
paths | string[] | The components of the path to join. |
separator β
pathSeparator: string = path.separator
Gets the string used to separate file paths.
API References β
- File class
- Folder class
- FileSystemEntity class
- knownFolders module
- path module
Native Component β
Android: java.io.File
iOS: NSFileManager
- How to work with files and folders
- Accessing the Documents folder
- Accessing the temporary(Caches) folder
- Accessing the root folder for the app
- Creating a folder
- Renaming a folder
- Check if a folder exists
- Accessing a folder's content
- Deleting the contents of a Folder
- Deleting a folder
- Creating, writing to and reading from a text file
- Check if a file exists
- Renaming a file
- Saving a binary data to a file
- Reading a binary data from a file
- Deleting a file
- Normalizing a path
- FileSystem API
- documents()
- externalDocuments()
- temp()
- currentApp()
- iOS known folders
- fromPath()
- getFolder
- exists
- isKnown
- lastModified
- name
- path
- parent
- remove()
- removeSync()
- rename()
- renameSync()
- getEntities()
- getEntitiesSync()
- eachEntity()
- getFile()
- extension
- size
- isLocked
- readText()
- readTextSync()
- read
- readSync()
- writeText()
- writeTextSync()
- write()
- writeSync()
- contains()
- clear()
- clearSync()
- path operations
- API References
- Native Component
Contributors
Last updated: