itinance / react-native-fs Goto Github PK
View Code? Open in Web Editor NEWNative filesystem access for react-native
License: MIT License
Native filesystem access for react-native
License: MIT License
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?
It looks like the current writeFile method wants the data to be base64 encoded. If I want to save the contents of data obtained using the JS network interface: https://facebook.github.io/react-native/docs/network.html#content, is there some way to avoid the base64 encoding step?
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
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!
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?
I'm saving a video to a temporary local directory. Once I'm done, I unlink the file which appears to succeed but the memory footprint of the app remains unchanged as if the file was not removed.
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?
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)
When download file from url failed,will cause app crash in iOS.
return callback(@[[NSNull null], @{@"jobId": jobId,
will throw an error
Thread 1: signal SIGABRT
This conflicts with other modules, like react-native-camera
. I've had to go back down to version 0.3.1
to avoid it.
There is an error: 'RCTBridgeModule.h' file not found.
Right now downloadFile does not follow redirects on Android where it does on iOS.
Some unicode characters and strings are not correctly read or written. This can be fixed by surrounding the decode with decodeURIComponent
and escape
when reading and doing the reverse on encoding when writing, as described in https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa#Unicode_Strings
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?
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]);
}
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;
}
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?
I have an assets-library://
link to an image in my Camera Roll. How can I save it to my apps Documents folder?
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.
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);
});
},
I'm getting an error:
'RCTRootView.h' file not found
I'm using a fresh build of react native 0.17.
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];
is possible to implement 'copy' function?
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"
Hi.
I'm trying to do program which will download mp3 from internet, save it and play. But all players that I found use "raw" folder for playing. Do you have any advise, how I can work with this folder?
See http://developer.android.com/reference/java/net/HttpURLConnection.html:
Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.
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?
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.)
It might be useful to allow appending to a file
It would be useful for some cases to be able to stream the data into a file / from a file.
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.
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}} />
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.
Just as the title suggests, is file uploading on the roadmap? Thanks.
This would make the method a bit more generic, and might allow reading from different dirs which aren't available as constants yet in the manager
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.
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
I download from npm, it can't use ExternalDirectoryPath, so please publish to npm
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
Is there any chance to support assets-library tag url? ex: assets-library://asset/asset.JPG?id=1A85E963-XXXX-XXXX-XXXX-A497490A93B9&ext=JPG
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
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.
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
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)
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
})
Right now best I can see is to use stat
and check error case.
To help manage dependencies via CocoaPods, please consider releasing as a pod.
See react-native-xml as an example.
@johanneslumpe Do you think it is reasonable to drop the 2nd argument and make readDir
take an absolute path? It's not an issue that can't be worked around but I think new comers might think this is a little odd?
I'm raising this now so we don't get design quirks set in stone when we reach version 1.0 :-)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.