Skip to content

Repository files navigation

React Native NitroFS

React Native NitroFS

npm versionDiscordnpm downloadsnpm downloadsmit licence

A high-performance file system module for React Native that provides native-speed file operations and network transfers using Swift (iOS) and Kotlin (Android) implementations.

🚀 Features

  • 📁 File Operations: Read, write, copy, delete, and manage files
  • 📂 Directory Management: Create, navigate, and manage directories
  • ⬆️ File Uploads: Upload files with progress tracking and multipart support
  • ⬇️ File Downloads: Download files with progress tracking
  • 🔍 File Inspection: Check existence, get file stats, and list directory contents
  • ⚡ Native Performance: Direct Swift/Kotlin implementations for optimal speed
  • 📱 Cross-Platform: Full support for iOS and Android
  • 🛡️ Error Handling: Comprehensive error handling with detailed messages
  • 💾 Memory Efficient: Optimized for large files with chunked reading

📋 Requirements

  • React Native: v0.78.0 or higher
  • Node.js: 18.0.0 or higher
  • Platforms: iOS 12.0+, Android API 21+

📦 Installation

# Using bun (recommended)
bun add react-native-nitro-fs react-native-nitro-modules@0.35.6
# Using npm
npm install react-native-nitro-fs react-native-nitro-modules@0.35.6
# Using yarn
yarn add react-native-nitro-fs react-native-nitro-modules@0.35.6

iOS Setup

cd ios && pod install

🎯 Quick Start

import{NitroFS}from'react-native-nitro-fs'// Basic file operationsconstexists=awaitNitroFS.exists('/path/to/file')constcontent=awaitNitroFS.readFile('/path/to/file','utf8')awaitNitroFS.writeFile('/path/to/file','Hello, World!','utf8')// Download with progressconstfile=awaitNitroFS.downloadFile({url: 'https://example.com/file.txt',destinationPath: NitroFS.DOWNLOAD_DIR+'/file.txt',},(downloadedBytes,totalBytes)=>{console.log(`Downloading ${(downloadedBytes/totalBytes)*100}%`)})// Upload with progressawaitNitroFS.uploadFile({filePath: '/path/to/file.txt',url: 'https://example.com/upload',method: 'POST',field: 'file',},(uploadedBytes,totalBytes)=>{console.log(`Uploading ${(uploadedBytes/totalBytes)*100}%`)})

📚 API Reference

Directory Constants

Access predefined directory paths for different use cases:

// Bundle directory (read-only, app resources)NitroFS.BUNDLE_DIR// Documents directory (user data, backed up)NitroFS.DOCUMENT_DIR// Cache directory (temporary data, not backed up)NitroFS.CACHE_DIR// Downloads directory (user downloads)NitroFS.DOWNLOAD_DIR

File System Operations

exists(path: string): Promise<boolean>

Check if a file or directory exists at the specified path.

// Check if file existsconstfileExists=awaitNitroFS.exists('/path/to/file.txt')// Check if directory existsconstdirExists=awaitNitroFS.exists('/path/to/directory')

writeFile(path: string, data: string, encoding: NitroFileEncoding): Promise<void>

Write data to a file. Creates parent directories automatically and performs atomic writes.

// Write text fileawaitNitroFS.writeFile(NitroFS.DOCUMENT_DIR+'/config.json',JSON.stringify({theme: 'dark'}),'utf8')// Write with different encodingawaitNitroFS.writeFile('/path/to/file.txt','Hello World','utf8')

Features:

  • ✅ Automatic parent directory creation
  • ✅ Atomic write operations
  • ✅ Disk space validation
  • ✅ Comprehensive error handling

readFile(path: string, encoding: NitroFileEncoding): Promise<string>

Read the contents of a file with optimized memory handling for large files.

// Read text fileconstcontent=awaitNitroFS.readFile('/path/to/file.txt','utf8')// Read JSON fileconstconfig=JSON.parse(awaitNitroFS.readFile('/path/to/config.json','utf8'))

Performance Features:

  • 🚀 Adaptive chunked reading for large files
  • 💾 Memory-efficient handling
  • ⚠️ Automatic size limits for very large files

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

Copy a file from source to destination.

// Copy file to documents directoryawaitNitroFS.copyFile('/path/to/source.txt',NitroFS.DOCUMENT_DIR+'/backup.txt')

copy(srcPath: string, destPath: string): Promise<void>

Copy a file or directory recursively.

// Copy entire directoryawaitNitroFS.copy('/path/to/source','/path/to/destination')

unlink(path: string): Promise<boolean>

Delete a file or directory.

// Delete fileawaitNitroFS.unlink('/path/to/file.txt')// Delete directory (recursive)awaitNitroFS.unlink('/path/to/directory')

mkdir(path: string): Promise<boolean>

Create a directory.

// Create single directoryawaitNitroFS.mkdir('/path/to/newdir')// Create nested directories (handled automatically)awaitNitroFS.mkdir('/path/to/nested/directories')

stat(path: string): Promise<NitroFileStat>

Get detailed information about a file or directory.

conststat=awaitNitroFS.stat('/path/to/file.txt')console.log({size: stat.size,// File size in bytesisDirectory: stat.isDirectory,isFile: stat.isFile,modifiedTime: stat.mtime,// Last modified timestampcreatedTime: stat.ctime,// Creation timestamp})

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

List contents of a directory.

// List all files and directoriesconstitems=awaitNitroFS.readdir('/path/to/directory')console.log('Directory contents:',items)

rename(oldPath: string, newPath: string): Promise<void>

Rename or move a file or directory.

// Rename fileawaitNitroFS.rename('/path/to/old.txt','/path/to/new.txt')// Move file to different directoryawaitNitroFS.rename('/path/to/file.txt','/new/path/file.txt')

Path Utilities

dirname(path: string): string

Get the directory name from a path.

constdir=NitroFS.dirname('/path/to/file.txt')// Returns: '/path/to'

basename(path: string): string

Get the filename from a path, including the file extension.

constname=NitroFS.basename('/path/to/file.txt')// Returns: 'file.txt'constnameWithExt=NitroFS.basename('/path/to/document.pdf')// Returns: 'document.pdf'

extname(path: string): string

Get the file extension from a path.

constext=NitroFS.extname('/path/to/file.txt')// Returns: '.txt'

Network Operations

uploadFile(uploadOptions: NitroUploadOptions, onProgress?: (uploadedBytes: number, totalBytes: number) => void): Promise<void>

Upload a file to a server with progress tracking and multipart support.

constuploadOptions={filePath: NitroFS.DOCUMENT_DIR+'/document.pdf',url: 'https://api.example.com/upload',method: 'POST',field: 'file',headers: {'Authorization': 'Bearer your-token','X-Custom-Header': 'value',},}awaitNitroFS.uploadFile(uploadOptions,(uploadedBytes,totalBytes)=>{constprogress=(uploadedBytes/totalBytes)*100console.log(`Upload progress: ${progress.toFixed(1)}%`)})

downloadFile(downloadOptions: NitroDownloadOptions, onProgress?: (downloadedBytes: number, totalBytes: number) => void): Promise<NitroFile>

Download a file from a server with progress tracking.

constdownloadOptions={url: 'https://example.com/files/document.pdf',destinationPath: NitroFS.DOWNLOAD_DIR+'/document.pdf',headers: {'Authorization': 'Bearer your-token',},}constdownloadedFile=awaitNitroFS.downloadFile(downloadOptions,(downloadedBytes,totalBytes)=>{constprogress=(downloadedBytes/totalBytes)*100console.log(`Download progress: ${progress.toFixed(1)}%`)})console.log('Downloaded file:',downloadedFile)// Returns: { name: 'document.pdf', mimeType: 'application/pdf', path: '/path/to/file' }

📝 Type Definitions

NitroFile

interfaceNitroFile{name: string// File name with extensionmimeType: string// MIME type (e.g., 'text/plain', 'application/pdf')path: string// Full file path}

NitroUploadOptions

interfaceNitroUploadOptions{filePath: string// Path to the file to uploadurl: string// Upload endpoint URLmethod?: 'POST'|'PUT'|'PATCH'// HTTP methodfield?: string// Form field nameheaders?: Record<string,string>// Custom headers}

NitroDownloadOptions

interfaceNitroDownloadOptions{url: string// Download endpoint URLdestinationPath: string// Path where the downloaded file is savedheaders?: Record<string,string>// Custom headers}

NitroFileStat

interfaceNitroFileStat{size: number// File size in bytesisDirectory: boolean// True if path is a directoryisFile: boolean// True if path is a filemtime: number// Last modified timestampctime: number// Creation timestamp}

NitroFileEncoding

typeNitroFileEncoding='utf8'|'ascii'|'base64'

🔧 Advanced Usage

Error Handling

try{constcontent=awaitNitroFS.readFile('/path/to/file.txt','utf8')console.log('File content:',content)}catch(error){if(error.message.includes('File does not exist')){console.log('File not found')}elseif(error.message.includes('Permission denied')){console.log('No permission to access file')}else{console.error('Unexpected error:',error.message)}}

Working with Large Files

// The library automatically handles large files efficientlyconstlargeFile=awaitNitroFS.readFile('/path/to/large-file.txt','utf8')// For very large files (>100MB), consider streaming or chunked processingconststat=awaitNitroFS.stat('/path/to/large-file.txt')if(stat.size>100*1024*1024){// 100MBconsole.log('Large file detected, consider streaming')}

Directory Navigation

// List all files in documents directoryconstfiles=awaitNitroFS.readdir(NitroFS.DOCUMENT_DIR)// Filter for specific file typesconsttextFiles=files.filter((file)=>file.endsWith('.txt'))// Get file stats for each filefor(constfileoffiles){constfilePath=`${NitroFS.DOCUMENT_DIR}/${file}`conststat=awaitNitroFS.stat(filePath)console.log(`${file}: ${stat.size} bytes`)}

File Backup Example

constbackupFile=async(sourcePath: string)=>{consttimestamp=newDate().toISOString().replace(/[:.]/g,'-')constbackupPath=`${NitroFS.DOCUMENT_DIR}/backup-${timestamp}.txt`try{awaitNitroFS.copyFile(sourcePath,backupPath)console.log('Backup created successfully')}catch(error){console.error('Backup failed:',error.message)}}

🚨 Common Issues & Solutions

Permission Errors

Issue: "Permission denied" errors on Android Solution: Ensure your app has the necessary permissions in AndroidManifest.xml:

<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE" />

Large File Handling

Issue: Memory issues with large files Solution: The library automatically handles large files with chunked reading, but you can implement custom streaming for very large files.

Network Timeouts

Issue: Upload/download operations hanging Solution: The library includes timeout handling, but you can implement custom timeout logic:

constuploadWithTimeout=async(options: NitroUploadOptions)=>{consttimeoutPromise=newPromise((_,reject)=>{setTimeout(()=>reject(newError('Upload timeout')),30000)})returnPromise.race([NitroFS.uploadFile(options),timeoutPromise])}

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

# Clone the repository
git clone https://github.com/patrickkabwe/react-native-nitro-fs.git
cd react-native-nitro-fs
# Install dependencies
bun install
# Run example appcd example
bun install
npx react-native run-ios # or run-android

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Credits

Bootstrapped with create-nitro-module.


Made with ❤️ for the React Native community

💬 Have any questions? Join our Discord channel

About

A high-performance file system module for React Native that handles file operations and transfers with native speed.

Resources

Stars

61 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages