πŸš€ 8.9 Released! β†’ ⚑️ New Node-API Engine Preview, πŸ“² ns widget ios, πŸ’… Tailwind v4 and more...
Read Announcement

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:

ts
import { knownFolders } from'@nativescript/core'

constdocuments= knownFolders.documents()

Accessing the temporary(Caches) folder ​

ts
import { knownFolders } from'@nativescript/core'

constcache= knownFolders.temp()

Accessing the root folder for the app ​

ts
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.

ts
folder.getFolder('folder-name')

You can also use the fromPath static method of the Folder class.

ts
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:

ts
folder
 .rename(newName)
 .then((res) => {
// Folder Successfully renamed.
 })
 .catch((err) => {
//Folder couldn't be renamed
 console.error(err)
 })

Check if a folder exists ​

ts
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:

ts
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:

ts
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:

ts
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 the Folder class and pass it the file name with the extension.
ts
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 or writeTextSync method:
ts
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:
ts
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:

ts
constexists= File.exists(filePath)

Renaming a file ​

To rename a file, use the rename or renameSync method:

ts
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:

ts
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:

ts
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:

ts
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:

ts
consttestPath='///test.txt'
let documentsFolder = knownFolders.documents()
path.normalize(documentsFolder.path + testPath)

FileSystem API ​

documents() ​

ts
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() ​

ts
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 the AndroidManifest.xml file:
xml
<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() ​

ts
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() ​

ts
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() ​

ts
constfolder:Folder= knownFolders.ios.library()

Gets the NSLibraryDirectory.


developer() ​

ts
constfolder:Folder= knownFolders.ios.developer()

Gets the NSDeveloperDirectory.


desktop() ​

ts
constfolder:Folder= knownFolders.ios.desktop()

Gets the NSDesktopDirectory.


downloads() ​

ts
constfolder:Folder= knownFolders.ios.downloads()

Gets the NSDownloadsDirectory.


movies() ​

ts
constfolder:Folder= knownFolders.ios.movies()

Gets the NSMoviesDirectory.


music() ​

ts
constfolder:Folder= knownFolders.ios.music()

Gets the NSMusicDirectory.


pictures() ​

ts
constfolder:Folder= knownFolders.ios.pictures()

Gets the NSPicturesDirectory.


sharedPublic() ​

ts
constfolder:Folder= knownFolders.ios.sharedPublic()

Gets the NSSharedPublicDirectory.


fromPath() ​

ts
constfile:File= File.fromPath(path)

or

ts
constfolder:Folder= Folder.fromPath(path)

Gets or creates a Folder or File entity at the specified path.


getFolder ​

ts
constfolder:Folder= folder.getFolder(name)

Gets or creates a Folder entity with the specified name within a Folder.


exists ​

ts
constfolderExists:boolean= Folder.exists(path)

or

ts
constfile:boolean= File.exists(path)

Checks whether a Folder or File with the specified path already exists.


isKnown ​

ts
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 ​

ts
constlastModified:Date= entity.lastModified

Gets the Date object specifying the last time this entity was modified.


name ​

ts
constname:string= entity.name

Gets the name of the entity.


path ​

ts
constpath:string= entity.path

Gets the fully-qualified path (including the extension for a File) of the entity.


parent ​

ts
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() ​

ts
constresult=await entity.remove()

Asynchronously removes (deletes) the current Entity from the file system.


removeSync() ​

ts
entity.removeSync(onError?: (error:any) => any): void

Removes (deletes) the current Entity from the file system.


rename() ​

ts
entity.rename(newName: string): Promise<any>

Asynchronously renames the current entity using the specified name.


renameSync() ​

ts
entity.renameSync(newName: string, onError?: (error:any) => any)

Renames the current entity synchronously, using the specified name.


getEntities() ​

ts
folder.getEntities(): Promise<Array<FileSystemEntity>>

Asynchronously gets all the top-level entities residing within a folder.


getEntitiesSync() ​

ts
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() ​

ts
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() ​

ts
folder.getFile(name: string): File

Gets or creates a File entity with the specified name within this Folder


extension ​

ts
constfileExt:string= file.extension

Gets the extension of the file.


size ​

ts
constfileSize:number= file.size

Gets the extension of the file.


isLocked ​

ts
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() ​

ts
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() ​

ts
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 ​

ts
constfileContent=await file.read()

Reads the binary content of the file asynchronously.


readSync() ​

ts
constfileContent= file.readSync(onError)

Reads the binary content of the file synchronously. onError is a function to be called if some IO-error occurs.

ParameterTypeDescription
onError?(error: any) => anyAn optional function to be called if some IO-error occurs.

writeText() ​

ts
constresult=await file.writeText(content, encoding)

Asynchronously writes the content of the file as a string using the specified encoding (defaults to UTF-8).

ParameterTypeDescription
contentstringThe content to write.
encoding?stringAn optional encoding value. If you do not pass any encoding, UTF-8 is used.

writeTextSync() ​

ts
file.writeTextSync(content, onError, encoding): void

Synchronously writes the content of the file as a string using the specified encoding (defaults to UTF-8).

ParameterTypeDescription
contentstringThe content to write.
onError?(error: any) => anyAn optional function to be called if some IO-error occurs.
encoding?stringAn optional encoding value. If you do not pass any encoding, UTF-8 is used.

write() ​

ts
await file.write(content)

Writes the provided binary content to the file asynchronously.

ParameterTypeDescription
contentanyThe content to write.

writeSync() ​

ts
file.writeSync(content: any, onError?: (error:any) => any): void

Writes the provided binary content to the file synchronously.

ParameterTypeDescription
contentanyThe content to write.
onError?(error: any) => anyAn optional function to be called if some IO-error occurs.

contains() ​

ts
constcontainsEntity:boolean= folder.contains(name)

Checks whether this Folder contains an Entity with the specified name.

ParameterTypeDescription
namestringThe name of the entity to check for.

clear() ​

ts
constresult=await folder.clear()

Asynchronously deletes all the files and folders (recursively), contained within the Folder.


clearSync() ​

ts
folder.clearSync(onError)

Synchronously deletes all the files and folders (recursively), contained within the Folder.

ParameterTypeDescription
onError?(error: any) => anyAn optional function to be called if some IO-error occurs.

path operations ​

normalize ​

ts
constnormalizedPath:string= path.normalize(path)

Normalizes a path, taking care of occurrences like .. and //.

ParameterTypeDescription
pathstringThe path to normalize.

join() ​

ts
constjoinedPath:string= path.join(...paths)

Joins all the provided string components, forming a valid and normalized path.

ParameterTypeDescription
pathsstring[]The components of the path to join.

separator ​

ts
pathSeparator: string = path.separator

Gets the string used to separate file paths.


API References ​

Native Component ​

Previous
Device
On this page
  1. How to work with files and folders
    1. Accessing the Documents folder
    2. Accessing the temporary(Caches) folder
    3. Accessing the root folder for the app
    4. Creating a folder
    5. Renaming a folder
    6. Check if a folder exists
    7. Accessing a folder's content
    8. Deleting the contents of a Folder
    9. Deleting a folder
    10. Creating, writing to and reading from a text file
    11. Check if a file exists
    12. Renaming a file
    13. Saving a binary data to a file
    14. Reading a binary data from a file
    15. Deleting a file
    16. Normalizing a path
  2. FileSystem API
    1. documents()
    2. externalDocuments()
    3. temp()
    4. currentApp()
    5. iOS known folders
    6. fromPath()
    7. getFolder
    8. exists
    9. isKnown
    10. lastModified
    11. name
    12. path
    13. parent
    14. remove()
    15. removeSync()
    16. rename()
    17. renameSync()
    18. getEntities()
    19. getEntitiesSync()
    20. eachEntity()
    21. getFile()
    22. extension
    23. size
    24. isLocked
    25. readText()
    26. readTextSync()
    27. read
    28. readSync()
    29. writeText()
    30. writeTextSync()
    31. write()
    32. writeSync()
    33. contains()
    34. clear()
    35. clearSync()
    36. path operations
  3. API References
  4. Native Component

Contributors

Edit this page

Last updated:

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /