Giter Site home page Giter Site logo

itinance / react-native-fs Goto Github PK

View Code? Open in Web Editor NEW
4.9K 4.9K 952.0 4.01 MB

Native filesystem access for react-native

License: MIT License

JavaScript 8.37% Objective-C 15.41% Java 13.76% Ruby 0.18% C# 30.99% C++ 31.13% C 0.16%
download filesystem react-native

react-native-fs's Introduction

react-native-fs

Native filesystem access for react-native

IMPORTANT

For RN < 0.57 and/or Gradle < 3 you MUST install react-native-fs at version @2.11.17!

For RN >= 0.57 and/or Gradle >= 3 you MUST install react-native-fs at version >= @2.13.2!

For RN >= 0.61 please install react-native-fs at version >= @2.16.0!

Table of Contents

  1. Changelog
  2. Usage
    1. iOS
    2. Android
    3. Windows
  3. Examples
  4. API
  5. Background Downloads Tutorial (iOS)
  6. Test / Demo App

Changelog

View the changelog here.

Usage (iOS/macOS)

First you need to install react-native-fs:

npm install react-native-fs --save

Note: If your react-native version is < 0.40 install with this tag instead:

npm install [email protected] --save

As @a-koka pointed out, you should then update your package.json to "react-native-fs": "2.0.1-rc.2" (without the tilde)

Adding automatically with react-native link

At the command line, in your project folder, type:

react-native link react-native-fs

Done! No need to worry about manually adding the library to your project.

Adding with CocoaPods

Add the RNFS pod to your list of application pods in your Podfile, using the path from the Podfile to the installed module:~~

pod 'RNFS', :path => '../node_modules/react-native-fs'

Install pods as usual:

pod install

Adding Manually in XCode

In XCode, in the project navigator, right click Libraries ➜ Add Files to [your project's name] Go to node_modules ➜ react-native-fs and add the .xcodeproj file

In XCode, in the project navigator, select your project. Add the lib*.a from the RNFS project to your project's Build Phases ➜ Link Binary With Libraries. Click the .xcodeproj file you added before in the project navigator and go the Build Settings tab. Make sure 'All' is toggled on (instead of 'Basic'). Look for Header Search Paths and make sure it contains both $(SRCROOT)/../react-native/React and $(SRCROOT)/../../React - mark both as recursive.

Run your project (Cmd+R)

Usage (Android)

Android support is currently limited to only the DocumentDirectory. This maps to the app's files directory.

Make alterations to the following files:

  • android/settings.gradle
...
include ':react-native-fs'
project(':react-native-fs').projectDir = new File(settingsDir, '../node_modules/react-native-fs/android')
  • android/app/build.gradle
...
dependencies {
    ...
    implementation project(':react-native-fs')
}
  • register module (in MainActivity.java)

    • For react-native below 0.19.0 (use cat ./node_modules/react-native/package.json | grep version)
import com.rnfs.RNFSPackage;  // <--- import

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {

  ......

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mReactRootView = new ReactRootView(this);

    mReactInstanceManager = ReactInstanceManager.builder()
      .setApplication(getApplication())
      .setBundleAssetName("index.android.bundle")
      .setJSMainModuleName("index.android")
      .addPackage(new MainReactPackage())
      .addPackage(new RNFSPackage())      // <------- add package
      .setUseDeveloperSupport(BuildConfig.DEBUG)
      .setInitialLifecycleState(LifecycleState.RESUMED)
      .build();

    mReactRootView.startReactApplication(mReactInstanceManager, "ExampleRN", null);

    setContentView(mReactRootView);
  }

  ......

}
  • For react-native 0.19.0 and higher
import com.rnfs.RNFSPackage; // <------- add package

public class MainActivity extends ReactActivity {
   // ...
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
        new MainReactPackage(), // <---- add comma
        new RNFSPackage() // <---------- add package
      );
    }
  • For react-native 0.29.0 and higher ( in MainApplication.java )
import com.rnfs.RNFSPackage; // <------- add package

public class MainApplication extends Application implements ReactApplication {
   // ...
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
        new MainReactPackage(), // <---- add comma
        new RNFSPackage() // <---------- add package
      );
    }

Usage (Windows)

Adding automatically with react-native link

The link command also works for adding the native dependency on Windows:

react-native link react-native-fs

Adding Manually in Visual Studio

Follow the instructions in the 'Linking Libraries' documentation on the react-native-windows GitHub repo. For the first step of adding the project to the Visual Studio solution file, the path to the project should be ../node_modules/react-native-fs/windows/RNFS/RNFS.csproj.

Examples

Basic

// require the module
var RNFS = require('react-native-fs');

// get a list of files and directories in the main bundle
RNFS.readDir(RNFS.MainBundlePath) // On Android, use "RNFS.DocumentDirectoryPath" (MainBundlePath is not defined)
  .then((result) => {
    console.log('GOT RESULT', result);

    // stat the first file
    return Promise.all([RNFS.stat(result[0].path), result[0].path]);
  })
  .then((statResult) => {
    if (statResult[0].isFile()) {
      // if we have a file, read it
      return RNFS.readFile(statResult[1], 'utf8');
    }

    return 'no file';
  })
  .then((contents) => {
    // log the file contents
    console.log(contents);
  })
  .catch((err) => {
    console.log(err.message, err.code);
  });

File creation

// require the module
var RNFS = require('react-native-fs');

// create a path you want to write to
// :warning: on iOS, you cannot write into `RNFS.MainBundlePath`,
// but `RNFS.DocumentDirectoryPath` exists on both platforms and is writable
var path = RNFS.DocumentDirectoryPath + '/test.txt';

// write the file
RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8')
  .then((success) => {
    console.log('FILE WRITTEN!');
  })
  .catch((err) => {
    console.log(err.message);
  });

File deletion

// create a path you want to delete
var path = RNFS.DocumentDirectoryPath + '/test.txt';

return RNFS.unlink(path)
  .then(() => {
    console.log('FILE DELETED');
  })
  // `unlink` will throw an error, if the item to unlink does not exist
  .catch((err) => {
    console.log(err.message);
  });

File upload (Android and IOS only)

// require the module
var RNFS = require('react-native-fs');

var uploadUrl = 'http://requestb.in/XXXXXXX';  // For testing purposes, go to http://requestb.in/ and create your own link
// create an array of objects of the files you want to upload
var files = [
  {
    name: 'test1',
    filename: 'test1.w4a',
    filepath: RNFS.DocumentDirectoryPath + '/test1.w4a',
    filetype: 'audio/x-m4a'
  }, {
    name: 'test2',
    filename: 'test2.w4a',
    filepath: RNFS.DocumentDirectoryPath + '/test2.w4a',
    filetype: 'audio/x-m4a'
  }
];

var upload
= (response) => {
  var jobId = response.jobId;
  console.log('UPLOAD HAS BEGUN! JobId: ' + jobId);
};

var uploadProgress = (response) => {
  var percentage = Math.floor((response.totalBytesSent/response.totalBytesExpectedToSend) * 100);
  console.log('UPLOAD IS ' + percentage + '% DONE!');
};

// upload files
RNFS.uploadFiles({
  toUrl: uploadUrl,
  files: files,
  method: 'POST',
  headers: {
    'Accept': 'application/json',
  },
  fields: {
    'hello': 'world',
  },
  begin: uploadBegin,
  progress: uploadProgress
}).promise.then((response) => {
    if (response.statusCode == 200) {
      console.log('FILES UPLOADED!'); // response.statusCode, response.headers, response.body
    } else {
      console.log('SERVER ERROR');
    }
  })
  .catch((err) => {
    if(err.description === "cancelled") {
      // cancelled by user
    }
    console.log(err);
  });

API

Constants

The following constants are available on the RNFS export:

  • MainBundlePath (String) The absolute path to the main bundle directory (not available on Android)
  • CachesDirectoryPath (String) The absolute path to the caches directory
  • ExternalCachesDirectoryPath (String) The absolute path to the external caches directory (android only)
  • DocumentDirectoryPath (String) The absolute path to the document directory
  • DownloadDirectoryPath (String) The absolute path to the download directory (on android and Windows only)
  • TemporaryDirectoryPath (String) The absolute path to the temporary directory (falls back to Caching-Directory on Android)
  • LibraryDirectoryPath (String) The absolute path to the NSLibraryDirectory (iOS only)
  • ExternalDirectoryPath (String) The absolute path to the external files, shared directory (android only)
  • ExternalStorageDirectoryPath (String) The absolute path to the external storage, shared directory (android only)
  • PicturesDirectoryPath (String) The absolute path to the pictures directory (Windows only)
  • RoamingDirectoryPath (String) The absolute path to the roaming directory (Windows only)

IMPORTANT: when using ExternalStorageDirectoryPath it's necessary to request permissions (on Android) to read and write on the external storage, here an example: React Native Offical Doc

readDir(dirpath: string): Promise<ReadDirItem[]>

Reads the contents of path. This must be an absolute path. Use the above path constants to form a usable file path.

The returned promise resolves with an array of objects with the following properties:

type ReadDirItem = {
  ctime: date;     // The creation date of the file (iOS only)
  mtime: date;     // The last modified date of the file
  name: string;     // The name of the item
  path: string;     // The absolute path to the item
  size: string;     // Size in bytes
  isFile: () => boolean;        // Is the item just a file?
  isDirectory: () => boolean;   // Is the item a directory?
};

readDirAssets(dirpath: string): Promise<ReadDirItem[]>

Reads the contents of dirpath in the Android app's assets folder. dirpath is the relative path to the file from the root of the assets folder.

The returned promise resolves with an array of objects with the following properties:

type ReadDirItem = {
  name: string;     // The name of the item
  path: string;     // The absolute path to the item
  size: string;     // Size in bytes.
  						// Note that the size of files compressed during the creation of the APK (such as JSON files) cannot be determined.
  						// `size` will be set to -1 in this case.
  isFile: () => boolean;        // Is the file just a file?
  isDirectory: () => boolean;   // Is the file a directory?
};

Note: Android only.

readdir(dirpath: string): Promise<string[]>

Node.js style version of readDir that returns only the names. Note the lowercase d.

stat(filepath: string): Promise<StatResult>

Stats an item at filepath. If the filepath is linked to a virtual file, for example Android Content URI, the originalPath can be used to find the pointed file path. The promise resolves with an object with the following properties:

type StatResult = {
  path:            // The same as filepath argument
  ctime: date;     // The creation date of the file
  mtime: date;     // The last modified date of the file
  size: number;     // Size in bytes
  mode: number;     // UNIX file mode
  originalFilepath: string;    // ANDROID: In case of content uri this is the pointed file path, otherwise is the same as path
  isFile: () => boolean;        // Is the file just a file?
  isDirectory: () => boolean;   // Is the file a directory?
};

readFile(filepath: string, encoding?: string): Promise<string>

Reads the file at path and return contents. encoding can be one of utf8 (default), ascii, base64. Use base64 for reading binary files.

Note: you will take quite a performance hit if you are reading big files

read(filepath: string, length = 0, position = 0, encodingOrOptions?: any): Promise<string>

Reads length bytes from the given position of the file at path and returns contents. encoding can be one of utf8 (default), ascii, base64. Use base64 for reading binary files.

Note: reading big files piece by piece using this method may be useful in terms of performance.

readFileAssets(filepath:string, encoding?: string): Promise<string>

Reads the file at path in the Android app's assets folder and return contents. encoding can be one of utf8 (default), ascii, base64. Use base64 for reading binary files.

filepath is the relative path to the file from the root of the assets folder.

Note: Android only.

readFileRes(filename:string, encoding?: string): Promise<string>

Reads the file named filename in the Android app's res folder and return contents. Only the file name (not folder) needs to be specified. The file type will be detected from the extension and automatically located within res/drawable (for image files) or res/raw (for everything else). encoding can be one of utf8 (default), ascii, base64. Use base64 for reading binary files.

Note: Android only.

writeFile(filepath: string, contents: string, encoding?: string): Promise<void>

Write the contents to filepath. encoding can be one of utf8 (default), ascii, base64. options optionally takes an object specifying the file's properties, like mode etc.

appendFile(filepath: string, contents: string, encoding?: string): Promise<void>

Append the contents to filepath. encoding can be one of utf8 (default), ascii, base64.

write(filepath: string, contents: string, position?: number, encoding?: string): Promise<void>

Write the contents to filepath at the given random access position. When position is undefined or -1 the contents is appended to the end of the file. encoding can be one of utf8 (default), ascii, base64.

moveFile(filepath: string, destPath: string): Promise<void>

Moves the file located at filepath to destPath. This is more performant than reading and then re-writing the file data because the move is done natively and the data doesn't have to be copied or cross the bridge.

Note: Overwrites existing file in Windows.

copyFolder(srcFolderPath: string, destFolderPath: string): Promise<void>

Copies the contents located at srcFolderPath to destFolderPath.

Note: Windows only. This method is recommended when directories need to be copied from one place to another.

copyFile(filepath: string, destPath: string): Promise<void>

Copies the file located at filepath to destPath.

Note: On Android and Windows copyFile will overwrite destPath if it already exists. On iOS an error will be thrown if the file already exists.

copyFileAssets(filepath: string, destPath: string): Promise<void>

Copies the file at filepath in the Android app's assets folder and copies it to the given destPath path.

Note: Android only. Will overwrite destPath if it already exists.

copyFileRes(filename: string, destPath: string): Promise<void>

Copies the file named filename in the Android app's res folder and copies it to the given destPath path. res/drawable is used as the source parent folder for image files, res/raw for everything else.

Note: Android only. Will overwrite destPath if it already exists.

(iOS only) copyAssetsFileIOS(imageUri: string, destPath: string, width: number, height: number, scale?: number, compression?: number, resizeMode?: string): Promise<string>

Not available on Mac Catalyst.

Reads an image file from Camera Roll and writes to destPath. This method assumes the image file to be JPEG file. This method will download the original from iCloud if necessary.

Parameters

imageUri string (required)

URI of a file in Camera Roll. Can be either of the following formats:

  • ph://CC95F08C-88C3-4012-9D6D-64A413D254B3/L0/001
  • assets-library://asset/asset.JPG?id=CC95F08C-88C3-4012-9D6D-64A413D254B3&ext=JPG
destPath string (required)

Destination to which the copied file will be saved, e.g. RNFS.TemporaryDirectoryPath + 'example.jpg'.

width number (required)

Copied file's image width will be resized to width. If 0 is provided, width won't be resized.

height number (required)

Copied file's image height will be resized to height. If 0 is provided, height won't be resized.

scale number (optional)

Copied file's image will be scaled proportional to scale factor from width x height. If both width and height are 0, the image won't scale. Range is [0.0, 1.0] and default is 1.0.

compression number (optional)

Quality of copied file's image. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality). Range is [0.0, 1.0] and default is 1.0.

resizeMode string (optional)

If resizeMode is 'contain', copied file's image will be scaled so that its larger dimension fits width x height. If resizeMode is other value than 'contain', the image will be scaled so that it completely fills width x height. Default is 'contain'. Refer to PHImageContentMode.

Return value

Promise<string>

Copied file's URI.

Video-Support

One can use this method also to create a thumbNail from a video in a specific size. Currently it is impossible to specify a concrete position, the OS will decide wich Thumbnail you'll get then. To copy a video from assets-library and save it as a mp4-file, refer to copyAssetsVideoIOS.

Further information: https://developer.apple.com/reference/photos/phimagemanager/1616964-requestimageforasset The promise will on success return the final destination of the file, as it was defined in the destPath-parameter.

(iOS only) copyAssetsVideoIOS(videoUri: string, destPath: string): Promise<string>

Not available on Mac Catalyst.

Copies a video from assets-library, that is prefixed with 'assets-library://asset/asset.MOV?...' to a specific destination.

unlink(filepath: string): Promise<void>

Unlinks the item at filepath. If the item does not exist, an error will be thrown.

Also recursively deletes directories (works like Linux rm -rf).

exists(filepath: string): Promise<boolean>

Check if the item exists at filepath. If the item does not exist, return false.

existsAssets(filepath: string): Promise<boolean>

Check in the Android assets folder if the item exists. filepath is the relative path from the root of the assets folder. If the item does not exist, return false.

Note: Android only.

existsRes(filename: string): Promise<boolean>

Check in the Android res folder if the item named filename exists. res/drawable is used as the parent folder for image files, res/raw for everything else. If the item does not exist, return false.

Note: Android only.

hash(filepath: string, algorithm: string): Promise<string>

Reads the file at path and returns its checksum as determined by algorithm, which can be one of md5, sha1, sha224, sha256, sha384, sha512.

touch(filepath: string, mtime?: Date, ctime?: Date): Promise<string>

Sets the modification timestamp mtime and creation timestamp ctime of the file at filepath. Setting ctime is supported on iOS and Windows, android always sets both timestamps to mtime.

mkdir(filepath: string, options?: MkdirOptions): Promise<void>

type MkdirOptions = {
  NSURLIsExcludedFromBackupKey?: boolean; // iOS only
};

Create a directory at filepath. Automatically creates parents and does not throw if already exists (works like Linux mkdir -p).

(IOS only): The NSURLIsExcludedFromBackupKey property can be provided to set this attribute on iOS platforms. Apple will reject apps for storing offline cache data that does not have this attribute.

downloadFile(options: DownloadFileOptions): { jobId: number, promise: Promise<DownloadResult> }

type DownloadFileOptions = {
  fromUrl: string;          // URL to download file from
  toFile: string;           // Local filesystem path to save the file to
  headers?: Headers;        // An object of headers to be passed to the server
  background?: boolean;     // Continue the download in the background after the app terminates (iOS only)
  discretionary?: boolean;  // Allow the OS to control the timing and speed of the download to improve perceived performance  (iOS only)
  cacheable?: boolean;      // Whether the download can be stored in the shared NSURLCache (iOS only, defaults to true)
  progressInterval?: number;
  progressDivider?: number;
  begin?: (res: DownloadBeginCallbackResult) => void; // Note: it is required when progress prop provided
  progress?: (res: DownloadProgressCallbackResult) => void;
  resumable?: () => void;    // only supported on iOS yet
  connectionTimeout?: number // only supported on Android yet
  readTimeout?: number       // supported on Android and iOS
  backgroundTimeout?: number // Maximum time (in milliseconds) to download an entire resource (iOS only, useful for timing out background downloads)
};
type DownloadResult = {
  jobId: number;          // The download job ID, required if one wishes to cancel the download. See `stopDownload`.
  statusCode: number;     // The HTTP status code
  bytesWritten: number;   // The number of bytes written to the file
};

Download file from options.fromUrl to options.toFile. Will overwrite any previously existing file.

If options.begin is provided, it will be invoked once upon download starting when headers have been received and passed a single argument with the following properties:

type DownloadBeginCallbackResult = {
  jobId: number;          // The download job ID, required if one wishes to cancel the download. See `stopDownload`.
  statusCode: number;     // The HTTP status code
  contentLength: number;  // The total size in bytes of the download resource
  headers: Headers;       // The HTTP response headers from the server
};

If options.progress is provided, it will be invoked continuously and passed a single argument with the following properties:

type DownloadProgressCallbackResult = {
  jobId: number;          // The download job ID, required if one wishes to cancel the download. See `stopDownload`.
  contentLength: number;  // The total size in bytes of the download resource
  bytesWritten: number;   // The number of bytes written to the file so far
};

If options.progressInterval is provided, it will return progress events in the maximum frequency of progressDivider. For example, if progressInterval = 100, you will not receive callbacks more often than every 100th millisecond.

If options.progressDivider is provided, it will return progress events that divided by progressDivider.

For example, if progressDivider = 10, you will receive only ten callbacks for this values of progress: 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 Use it for performance issues. If progressDivider = 0, you will receive all progressCallback calls, default value is 0.

(IOS only): options.background (Boolean) - Whether to continue downloads when the app is not focused (default: false) This option is currently only available for iOS, see the Background Downloads Tutorial (iOS) section.

(IOS only): If options.resumable is provided, it will be invoked when the download has stopped and and can be resumed using resumeDownload().

stopDownload(jobId: number): void

Abort the current download job with this ID. The partial file will remain on the filesystem.

(iOS only) resumeDownload(jobId: number): void

Resume the current download job with this ID.

(iOS only) isResumable(jobId: number): Promise<bool>

Check if the the download job with this ID is resumable with resumeDownload().

Example:

if (await RNFS.isResumable(jobId) {
    RNFS.resumeDownload(jobId)
}

(iOS only) completeHandlerIOS(jobId: number): void

For use when using background downloads, tell iOS you are done handling a completed download.

Read more about background downloads in the Background Downloads Tutorial (iOS) section.

uploadFiles(options: UploadFileOptions): { jobId: number, promise: Promise<UploadResult> }

options (Object) - An object containing named parameters

type UploadFileOptions = {
  toUrl: string;            // URL to upload file to
  binaryStreamOnly?: boolean// Allow for binary data stream for file to be uploaded without extra headers, Default is 'false'
  files: UploadFileItem[];  // An array of objects with the file information to be uploaded.
  headers?: Headers;        // An object of headers to be passed to the server
  fields?: Fields;          // An object of fields to be passed to the server
  method?: string;          // Default is 'POST', supports 'POST' and 'PUT'
  begin?: (res: UploadBeginCallbackResult) => void;
  progress?: (res: UploadProgressCallbackResult) => void;
};
type UploadResult = {
  jobId: number;        // The upload job ID, required if one wishes to cancel the upload. See `stopUpload`.
  statusCode: number;   // The HTTP status code
  headers: Headers;     // The HTTP response headers from the server
  body: string;         // The HTTP response body
};

Each file should have the following structure:

type UploadFileItem = {
  name: string;       // Name of the file, if not defined then filename is used
  filename: string;   // Name of file
  filepath: string;   // Path to file
  filetype: string;   // The mimetype of the file to be uploaded, if not defined it will get mimetype from `filepath` extension
};

If options.begin is provided, it will be invoked once upon upload has begun:

type UploadBeginCallbackResult = {
  jobId: number;        // The upload job ID, required if one wishes to cancel the upload. See `stopUpload`.
};

If options.progress is provided, it will be invoked continuously and passed a single object with the following properties:

type UploadProgressCallbackResult = {
  jobId: number;                      // The upload job ID, required if one wishes to cancel the upload. See `stopUpload`.
  totalBytesExpectedToSend: number;   // The total number of bytes that will be sent to the server
  totalBytesSent: number;             // The number of bytes sent to the server
};

Percentage can be computed easily by dividing totalBytesSent by totalBytesExpectedToSend.

(iOS only) stopUpload(jobId: number): Promise<void>

Abort the current upload job with this ID.

getFSInfo(): Promise<FSInfoResult>

Returns an object with the following properties:

type FSInfoResult = {
  totalSpace: number;   // The total amount of storage space on the device (in bytes).
  freeSpace: number;    // The amount of available storage space on the device (in bytes).
};

(Android only) scanFile(path: string): Promise<string[]>

Scan the file using Media Scanner.

(Android only) getAllExternalFilesDirs(): Promise<string[]>

Returns an array with the absolute paths to application-specific directories on all shared/external storage devices where the application can place persistent files it owns.

(iOS only) pathForGroup(groupIdentifier: string): Promise<string>

groupIdentifier (string) Any value from the com.apple.security.application-groups entitlements list.

Returns the absolute path to the directory shared for all applications with the same security group identifier. This directory can be used to to share files between application of the same developer.

Invalid group identifier will cause a rejection.

For more information read the Adding an App to an App Group section.

Background Downloads Tutorial (iOS)

Background downloads in iOS require a bit of a setup.

First, in your AppDelegate.m file add the following:

#import <RNFSManager.h>

...

- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
{
  [RNFSManager setCompletionHandlerForIdentifier:identifier completionHandler:completionHandler];
}

The handleEventsForBackgroundURLSession method is called when a background download is done and your app is not in the foreground.

We need to pass the completionHandler to RNFS along with its identifier.

The JavaScript will continue to work as usual when the download is done but now you must call RNFS.completeHandlerIOS(jobId) when you're done handling the download (show a notification etc.)

BE AWARE! iOS will give about 30 sec. to run your code after handleEventsForBackgroundURLSession is called and until completionHandler is triggered so don't do anything that might take a long time (like unzipping), you will be able to do it after the user re-launces the app, otherwide iOS will terminate your app.

Test / Demo app

Test app to demostrate the use of the module. Useful for testing and developing the module:

https://github.com/cjdell/react-native-fs-test

react-native-fs's People

Contributors

af avatar agenthunt avatar aichamorro avatar alexey-pkv avatar anshul-kai avatar autoreleasefool avatar avmoroz avatar byeokim avatar ccorcos avatar cjdell avatar corbt avatar edtorbett avatar freshlybakedcode avatar gensc004 avatar grabbou avatar itinance avatar jamesreggio avatar jarvisluong avatar jgreen01su avatar jnpdx avatar johanneslumpe avatar joshuapinter avatar juhasuni avatar kitolog avatar leoek avatar naxel avatar rozele avatar sbeca avatar superandrew213 avatar thomas101 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-fs's Issues

What do I need to use in my project.

I'm trying to use this on iOS. I installed 'react-native-fs' then added the 'libsqlite3.tbd' library and then installed 'bluebird' but I'm still getting "Error: undefined is not an object (evaluating 'RNFSManager.readDir')". What can I do to fix this error?

react-native 0.17 android error

I followed your steps faithfully based on the standard project just to make things simple, however I got this:

JS server already running.
Building and installing the app on the device (cd android && ./gradlew installDebug)...

FAILURE: Build failed with an exception.

* Where:
Build file '/media/Storage/easyship/android/build.gradle' line: 9

* What went wrong:
A problem occurred evaluating root project 'easyship'.
> Could not find method compile() for arguments [project ':react-native-fs'] on org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@501df9bd.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 1.629 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

Any idea on how to fix this?... your library is just what I need now and I find no replacement for it.

[Q] Cancelling pending download

Hey,

In my implementation, I have a queue of items to be downloaded. I am about to implement stopDownload however, I've noticed weird behaviour on iOS I wanted to double check with you.

When I call fs.unlink on a path that I previously used with fs.downloadFile and that operation has not finished yet - it will resolve successfully after the file is downloaded, however, fs.readdir call will not have that file.

Is that expected? Feels a bit weird, especially given that in readme it says "partial files will remain on file system"

Android: Media Scanner

Hi,

I noticed that when new images (or any file) are created under a location aka PicturesDirectoryPath they don't become visible immediately under the gallery app. The reason for that seems it requires an extra step to tell the android's mediascanner about the new files. By not doing that means the new files are going to get "visible" for users only when mediascanner starts which happens during the boot.

Following bellow a stackoverflow about this issue:
http://stackoverflow.com/questions/9414955/trigger-mediascanner-on-specific-path-folder-how-to

Cheers

readDir called with null on Android yields `NullPointerException`

java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
     at java.io.File.fixSlashes(File.java:183)
     at java.io.File.<init>(File.java:130)
     at com.rnfs.RNFSManager.readDir(RNFSManager.java:123)
     at java.lang.reflect.Method.invoke(Native Method)

Have working Android implementation, need to integrate somehow...

I've been working on an Android port as I really need cross platform support. Documentation on creating reusable modules supporting Android is still weak but I have succeeded in creating a demo project from scratch which demonstrates a sample app working on both platforms:
https://github.com/cjdell/react-native-fs

Here is Java implementation itself:
https://github.com/cjdell/react-native-fs/blob/master/android/app/src/main/java/com/rnfs/RNFSManager.java

I've tried to mirror your existing API closely but the current FS abstraction may need to change a little, i.e. Android doesn't have the concept of a documents directory as such.

Would be good to merge this with your module somehow, though not quite ready for pull request yet. I'm putting this out there in case there are others who want this. Please let me know how I can help out, it would be good to have Android support in this module :-)

Thanks

stopDownload() doesn't return a Promise

The readme indicates that it should, but I'm not sure if that's a docs error. Every other call in the API returns a Promise, so I'm guessing that would be the intended behaviour.

[Question] Loading an image saved to a path from RNFS

Hi,

I'm using gl-react-native and use their captureFrame method to save an image to file. I use RNFS to get the path for this file. If I lookup the path I can see that the image is there and can be reviewed using a normal image application.

However, when I want to require() it in an Image tag, I get the error that it cannot be resolved. The path is:
"file:///Users/alex/Library/Developer/CoreSimulator/Devices/6955A1DF-7189-4FD1-91EE-AFE106019086/data/Containers/Data/Application/F19A2400-3339-4C01-9FAA-FB36AE54C00E/Library/Caches/image.png"

Any idea why I cannot require this to show it as an image? I tried with and without the file://, I tried making it a relative path from the MainBundle path but none of them give me the image. Is there something obvious I'm overlooking?

It doesnt work on Android or iOS on either device or simulator.

(RN 0.21 if it matters)

Cheers

Access to /tmp directory?

Hi,

Thanks for the great work! It's been very helpful so far.

I was wondering if there is a way to access the /tmp directory?

Thanks,
Andrea

Release a version for new download features

At this time, the version on npm is 1.0.0, without new download features. I'm tried use the github version but it seams build fail. Can you release a version with these cool new features?

Could not read file at path rct-image-store://0

This type of path is returned by the default native module ImageEditingManager.cropImage.

Would this be possible to implement? You can show the image normally via <Image source={{uri: rct-image-store://0}} />

Inconsistent Saving Implementation

There seem to be two different methods being used to save NSData and I am not sure why:

BOOL success = [[NSFileManager defaultManager] createFileAtPath:filepath contents:data attributes:attributes];

BOOL success = [urlData writeToFile:filepath atomically:YES];

make compatible with node fs API

would be cool to be able to use this to shim node's fs

"browser": {
  "fs": "react-native-fs"
}
// then use as node fs
var fs = require('fs')
fs.readFile('path/to/file', options, function(err, buf) {
  // etc
})

jobId in progressCallback of downloadFile

I'm actually working on a loader that start multiple downloads and save state into an object that contain all jobs, in purpose to do a loading screen.

I just noticed that progressCallback doesn't contain the property jobId as beginCallback does. It's fine when a single file is downloaded, but with multiple downloads we can't easily associate the progress callback with his job.

Is there a reason for not returning this property? It seems simple enough since progressCallback listen progression with the jobId on both platforms.

Poor/empty exception messages on Android

I struggled to fix the download correctness issue in PR #62 due to the JS error messages being empty on Android. (We were just getting an empty Error object.)

Ideally JS errors and/or logging should provide information from the Java exception. As a quick hack, the below change to RNFSManager.java helped a lot. It turned out to be an HTTP 404 error and was easy to fix after knowing the issue.

I'm not submitting this as a pull request just yet because I suspect react-native may already provide a built-in Exception-to-JS-Error conversion utility function - any thoughts from RN Android devs?

private WritableMap makeErrorPayload(Exception ex) {
WritableMap error = Arguments.createMap();

// https://stackoverflow.com/questions/7242596/e-printstacktrace-in-string
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
String s = writer.toString();

//error.putString("message", ex.getMessage());
error.putString("message", s);
// TODO: Consolidate and move ex.printStackTrace() here?

return error;

}

[Question] Is it possible to move a folder from bundle to documents directory?

I want to move a folder from bundle directory to document directory, but when I implementing this using RNFS.move method, it throw an error which says “p72DF976CA7517E265BD17-1456993742” couldn’t be moved because you don’t have permission to access “Documents” on real device with cable plugged in. But I could move such a folder on simulator. Also I can download files to document folder on real device using another plugin, so I think I have that permission.

Any ideas?

White Screen

Hello,

I have an issue on this package, I follow the steps to add the package on Xcode but when I try to import or require RNFS I got a white screen.

Support assets-library tag

Is there any chance to support assets-library tag url? ex: assets-library://asset/asset.JPG?id=1A85E963-XXXX-XXXX-XXXX-A497490A93B9&ext=JPG

please publish to npm

I download from npm, it can't use ExternalDirectoryPath, so please publish to npm

react-native 0.16 compatible ?

Hi,

I'm trying to use your project with my react-native 0.16 project but I have the following error in Chrome console :

Unhandled rejection Error: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
    at convertError (http://localhost:8081/index.android.bundle?platform=android&dev=true:56761:11)
    at tryCatcher (http://localhost:8081/index.android.bundle?platform=android&dev=true:61503:15)
    at Promise._settlePromiseFromHandler (http://localhost:8081/index.android.bundle?platform=android&dev=true:59609:21)
    at Promise._settlePromiseAt (http://localhost:8081/index.android.bundle?platform=android&dev=true:59683:6)
    at Promise._settlePromises (http://localhost:8081/index.android.bundle?platform=android&dev=true:59799:6)
    at Async._drainQueue (http://localhost:8081/index.android.bundle?platform=android&dev=true:57089:4)
    at Async._drainQueues (http://localhost:8081/index.android.bundle?platform=android&dev=true:57099:6)
    at Async.drainQueues (http://localhost:8081/index.android.bundle?platform=android&dev=true:56981:6)
    at JSTimersExecution.callbacks.(anonymous function) (http://localhost:8081/index.android.bundle?platform=android&dev=true:3845:13)
    at Object.JSTimersExecution.callTimer (http://localhost:8081/index.android.bundle?platform=android&dev=true:3378:1)
    at http://localhost:8081/index.android.bundle?platform=android&dev=true:3434:19
    at Array.forEach (native)
    at Object.JSTimersExecution.callImmediatesPass (http://localhost:8081/index.android.bundle?platform=android&dev=true:3433:16)
    at Object.JSTimersExecution.callImmediates (http://localhost:8081/index.android.bundle?platform=android&dev=true:3449:25)
    at http://localhost:8081/index.android.bundle?platform=android&dev=true:2788:43
    at guard (http://localhost:8081/index.android.bundle?platform=android&dev=true:2712:1)

Remove photo

Hi,

I have this url assets-library://asset/asset.JPG?id=F970CE98-0BB8-400B-B4C8-AF7A938CF775&ext=JPG which I am trying to delete, which i get from react-native-camera

I tried to prefix it with both LibraryDirectoryPath and DocumentDirectoryPath, and without a prefix. The catch method is invoked and the err.message tells me that the file does not exist.

Any suggestion on how to use fs to delete the photo?

Path to file in Android package

I'm trying to use react-native-fs in conjunction with react-native-pdf-view. The goal is to bundle my app with a PDF file that can be displayed inside an Android app.

What I can't figure out is how to get a path to that PDF file that's inside the Android package. It's not in the files or caches folder, it's inside the Android package (bundle?) itself.

How can I get a path to that PDF file?

Allow reading a file from main bundle

It's not possible to read a file from a constant integer directory identifier (only from a path string) and there's no way to get the main bundle's path string to send to readFile. If can support the latter in pathForBundle, it is not necessary to change the readFile function. Changing pathForBundle to get the main bundle is fairly simple:

RCT_EXPORT_METHOD(pathForBundle:(NSString *)bundleNamed
                  callback:(RCTResponseSenderBlock)callback)
{
    if (bundleNamed.length == 0) {
        // no bundle name: return main bundle path
        callback(@[[NSNull null], [NSBundle mainBundle].bundlePath]);
        return;
    }
    NSString *path = [[NSBundle mainBundle].bundlePath stringByAppendingFormat:@"/%@.bundle", bundleNamed];
    NSBundle *bundle = [NSBundle bundleWithPath:path];
    if (!bundle.isLoaded) {
        [bundle load];
    }

    callback(@[[NSNull null], path]);
}

dataWithContentsOfURL Not Suggested for Downloading Files from Network

downloadFile uses dataWithContentsOfURL which per the Apple docs, is not ideal:

Discussion
This method is ideal for converting data:// URLs to NSData objects, and can also be used for reading short files synchronously. If you need to read potentially large files, use inputStreamWithURL: to open a stream, then read the file a piece at a time.

IMPORTANT
Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.

Instead, for non-file URLs, consider using the dataTaskWithURL:completionHandler: method of the NSURLSession class. See URL Session Programming Guide for details.

[iOS] downloadFile -> Error: Failed to create target file..

Hi,
following your example, I'd like to download the image of Earth to my Documents directory. However, the lines

RNFS.downloadFile(downloadUrl1, RNFS.DocumentDirectoryPath, begin1, progress1).then(res => {
    console.log("downloadFileTest success: ", JSON.stringify(res))
})
.catch(err => {
    console.log("downloadFileTest error: ", err)
});

result in an error:

downloadFileTest error:  Error: Failed to create target file at path: /Users/steff/Library/Developer/CoreSimulator/Devices/11B2BEE1-12AE-458A-9D9D-383356C128CC/data/Containers/Data/Application/2F7D9B96-D893-4DBC-A24F-086F14046CF2/Documents
    at convertError (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:75497:11)
    at tryCatcher (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:25554:15)
    at Promise._settlePromiseFromHandler (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:23660:21)
    at Promise._settlePromiseAt (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:23734:6)
    at Promise._settlePromises (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:23850:6)
    at Async._drainQueue (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:21140:4)
    at Async._drainQueues (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:21150:6)
    at Async.drainQueues (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:21032:6)
    at JSTimersExecution.callbacks.(anonymous function) (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:28391:13)
    at Object.JSTimersExecution.callTimer (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:28057:1)
    at Object.JSTimersExecution.callImmediatesPass (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:28115:19)
    at Object.JSTimersExecution.callImmediates (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:28130:25)
    at http://localhost:8081/index.ios.bundle?platform=ios&dev=true:27529:43
    at guard (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:27443:1)
    at MessageQueue.__callImmediates (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:27529:1)
    at http://localhost:8081/index.ios.bundle?platform=ios&dev=true:27499:8

Creating a folder in my Documents directory worked fine though. Any ideas? Thanks!

How to save blob or binary data

response is a blob....

writeBlob(response){
return RNFS.writeFile(this.path + '/' + 'first.pdf', response, 'base64')
.then((success) => {
console.log('FILE WRITTEN!');
})
.catch((err) => {
console.log(err.message);
});
},

confusing error message for readDir failure

Notably, readDir('/storage/emulated/0/') works just fine.

Reproduce with: https://github.com/outofculture/fsError

adb logcat | grep -i boom should show the error: Error: Attempt to get length of null array. You could get rid of the try/catch to get a stack trace, though it's only of the js, so it doesn't really show what's happening in the java.

(Sorry the example isn't exactly minimal; I'm also trying to track down a bug with what I think is redux interacting poorly with -fs.)

downloadFile() when app goes into the background

I'm finding that for some large file downloads, the app going into the background (or the phone locking due to inactivity) is causing downloads via downloadFile() to fail with an error. Is there any workaround to support background downloads?

Download percentage

Is there a way to get the download percentage?

RNFS.downloadFile('http://test.com/download.zip',RNFS.DocumentDirectoryPath + '/download.zip')

I would like to show a loader bar or show the user how long will it take to finish the download. I haven't seen anything in the docs.

Regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.