Browse by type
Native filesystem access for react-native
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!
View the changelog here.
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 react-native-fs@2.0.1-rc.2 --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)
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.
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
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)
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);
}
......
}
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
);
}
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
);
}
The link command also works for adding the native dependency on Windows:
react-native link react-native-fs
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.
// 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);
});
// 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);
});
// 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);
});
// 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);
});
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 directoryExternalCachesDirectoryPath (String) The absolute path to the external caches directory (android only)DocumentDirectoryPath (String) The absolute path to the document directoryDownloadDirectoryPath (String) The absolute path to the download directory (on android 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)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.
$ claude mcp add react-native-fs \
-- python -m otcore.mcp_server <graph>