Skip to content

FileSystem

Matheus Alves edited this page Jul 30, 2019 · 20 revisions

Accessing the File System

This module allow access to the file system of the device. You can create file; write/append data to a created file; list files of a directory and more.

import { FileSystem } from 'react-native-androide';

To use this module it's necessary garant the access to write on the file system. To grant the required permission, add this line:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> to the Manifest File located in android\app\src\main\AndroidManifest.xml.

Then, call FileSystem.requestPermission(). This function is async. When called, this functions ask the user to grant the access, then the promise is resolved with true if the user accepted the request or otherwise resolves with false. Example:

if(!await FileSystem.requestPermission()) {
	AndroidToast.show('Access Denied to filesystem', AndroidToast.SHORT);
	// Work around the access denied from the user
}

If this permission are not guaranteed the promises of all functions of this module will be rejected.

Some useful constants

This module provide some paths to known folders of the android system. The paths can be accessed by the constants listed below:

FileSystem.DownloadDir;  // The default path to the Download folder.
FileSystem.DocumentsDir; // The default path to the Documents folder. Available only in Android 4.4(API 19) or newer
FileSystem.DCIMDir; // The default path to the user camera images folder
FileSystem.PictureDir; // The default path to the pictures that is available to the user
FileSystem.MusicDir; // The default path to the Music folder
FileSystem.RingtoneDir; // The default path to the Ringtone folder
FileSystem.DataAppDir; // The path to the installation folder of you App
FileSystem.RootDir; // The path to the Root of the system
FileSystem.ExternalFilesDir; // The path to the files directory in the external storage
FileSystem.separator; // The separator charactere of the filesystem, aka "/"

Beware, there is no guarantee that these folders actually exists.

Listing files

To list files and subdirectories from a path call: FileSystem.ls(path). Where path stand for the full path of the directory. The function returns a Promise that, when resolved, give to you a Array of Objects.
The objects on the array have 3 keys:
name, a string with the name of the file;
isDir, a boolean that stands for if is a directory or not;
size, a Number that represents the number of bytes of the file.

let list = await FileSystem.ls(FileSystem.DownloadDir);
console.log(list);
/*
  EXAMPLE OUTPUT:

[
  {
    name: "some file.txt",
    isDir: false,
    size: 1024
  },
  {
    name: "small picture.png",
    isDir: false,
    size: 2048
  },
  {
    name: "sub folder",
    isDir: true,
    size: 0
  }
]
*/

If you have no access to the file system or the path is invalid, the pomise will be rejected.

Create a file

To create a file call FileSystem.mkfile(path). path must be the full path to the new file.
This function returns a promise, example:

try {
  await FileSystem.mkfile(FileSystem.DocumentsDir+FileSystem.separator+"newfile.txt");
} catch(err) {
  // work around
}

If any problem occur and the file is not created, the promise is rejected.

Create Directory

To create a directory call FileSystem.mkdirs(path). path must be the full path to the new folder. This function returns a promise.

This function will create any necessary parent path to the new directory, for example:

try {
  // This one will just create "newDir" inside documents dir
  await FileSystem.mkdirs(FileSystem.DocumentsDir
                          +FileSystem.separator
                          +"newDir");

  // This will create "subDirectory" inside documents dir,
  // and then will create "subSubDirectory" inside "subDirectory"
  await FileSystem.mkdirs(FileSystem.DocumentsDir
                          +FileSystem.separator
                          +"subDirectory"
                          +FileSystem.separator
                          +"subSubDirectory");
} catch(err) {
  // work around
}

Rename file

To rename a file call FileSystem.rename(path, newName). path must be the full path to the file and newName is just the new name of the file.
This function returns a promise, example:

try {
  await FileSystem.rename(FileSystem.DocumentsDir+FileSystem.separator+"file.txt", "renamedFile.txt");
} catch(err) {
  // work around
}

If any problem occur and the file is not renamed, the promise is rejected.

Check if a file or directory exists

To check if a file or directory exists call FileSystem.exists(path) path must be the full path. The returned promise will resolve with true or false, and will reject in case of any error, like ivalid path.

let exist = null;
try {
  exist = await FileSystem.exists(FileSystem.DocumentsDir+FileSystem.separator+"some song.mp3");
} catch(err) {
  // work around
}

Read file

To read a file you will use FileSystem.read(path). path must be the full path to a existing file. This function will return a Promise that resolves with all data from the file encoded in Base64.
You can decode the data from Base64 using the function FileSystem.base64Decode() described below.

let allData = "";
try {
  allData = await FileSystem.read(FileSystem.DocumentsDir+FileSystem.separator+"some song.mp3");
} catch(err) {
  console.log(err.message);
  // work around
}

The promise can be rejected for some reasons(like file not exists, path invalid and so on), so take better care of this.

Write File

To write in a file you will call FileSystem.write(path, data, append);
<String> path is the full path to an existing file.
<String> data is the full data encoded in Base64.
<boolean> append (optional) It's if the data must be placed on the end of the file or not.

Example:

let fullPath = FileSystem.DocumentsDir+FileSystem.separator+"test.txt";
try {
  let dataEncoded = await FileSystem.base64Encode("Test string to be written to a file");
  // Write data to a file and overwrite any existing data
  await FileSystem.write(fullPath, dataEncoded);
  // The file test.txt in Documents folder now have "Test string to be written to a file"

  // Appending more data
  let moreData = await FileSystem.base64Encode("\n Line 02");
  await FileSystem.write(fullPath, moreData, true);
  /* The file test.txt in Documents folder now have:
    "Test string to be written to a file
     Line 02"
  */
} catch(err) {
   // Failed to write, work around
}

Deleting files and folders

To delete a file or folder call FileSystem.rm(path);. This is a async function that, when resolved, ensures that the file has been deleted. The promise will reject if the path is invalid or you have no access to the File System.

Caution! If path is a directory, all the files and sub directories will be deleted.

// Deleting the "test.txt" inside Documents dir
FileSystem.rm(FileSystem.DocumentsDir+FileSystem.separator+"test.txt");

// Deleting the documents dir and ALL files and folders from it
FileSystem.rm(FileSystem.DocumentsDir);

Base64 Encode/Decode

To use properly this module, it's important encode data before write in a file.

  let dataEncoded = await FileSystem.base64Encode("Test string to be written to a file");

Additionally FileSystem.read(path) aways return a Base64 encoded data. To decode, you can do:

  let dataDecoded = await FileSystem.base64Decode(dataEncoded);

Note: Both functions is async, so you need to use await or .then() sintax.

Clone this wiki locally