@datacomvn/file-opener
v0.1.9
Published
React Native file opener of Datacom Vietnam
Maintainers
Readme
@datacomvn/file-opener
A high-performance React Native library for opening files with native viewers
Built with ⚡ Nitro Modules for blazing-fast performance
✨ Features
- 🚀 High Performance: Built with Nitro Modules for native-level performance
- 📱 Cross Platform: Works seamlessly on both iOS and Android
- 🎯 Smart File Detection: Automatically detects file types and opens with appropriate viewers
- 📄 Wide Format Support: Supports 50+ file formats including documents, images, videos, and more
- 🔒 Secure: Uses platform-native security mechanisms for file access
- 💾 Lightweight: Minimal bundle size impact
- 🛡️ Type Safe: Full TypeScript support with complete type definitions
🏗️ Installation
Using npm
npm install @datacomvn/file-opener react-native-nitro-modulesUsing yarn
yarn add @datacomvn/file-opener react-native-nitro-modulesUsing pnpm
pnpm add @datacomvn/file-opener react-native-nitro-modulesNote:
react-native-nitro-modulesis a required peer dependency as this library is built on Nitro Modules.
Platform Setup
iOS
No additional setup required. The library uses iOS's native QuickLook framework.
Android
Add the following to your android/app/src/main/AndroidManifest.xml:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>Create android/app/src/main/res/xml/file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="external_files" path="." />
<external-cache-path name="external_cache" path="." />
<files-path name="files" path="." />
<cache-path name="cache" path="." />
</paths>🚀 Quick Start
import { FileOpener } from '@datacomvn/file-opener';
// Open a PDF file
const success = FileOpener.open('/path/to/document.pdf');
if (success) {
console.log('File opened successfully!');
} else {
console.error('Failed to open file');
}📖 API Reference
FileOpener.open(path: string): boolean
Opens a file with the system's default application for that file type.
Parameters
path(string): Absolute path to the file to be opened
Returns
boolean:trueif the file was successfully opened,falseotherwise
Example
import { FileOpener } from '@datacomvn/file-opener';
import RNFS from 'react-native-fs';
// Example: Open a downloaded PDF
const downloadAndOpen = async () => {
try {
const downloadDest = `${RNFS.DocumentDirectoryPath}/sample.pdf`;
const download = RNFS.downloadFile({
fromUrl: 'https://example.com/sample.pdf',
toFile: downloadDest,
});
const result = await download.promise;
if (result.statusCode === 200) {
const opened = FileOpener.open(downloadDest);
if (opened) {
console.log('PDF opened successfully!');
} else {
console.error('Failed to open PDF');
}
}
} catch (error) {
console.error('Download failed:', error);
}
};📋 Supported File Types
The library supports a wide range of file formats:
Documents
- PDF:
.pdf - Microsoft Office:
.doc,.docx,.xls,.xlsx,.ppt,.pptx - Text:
.txt,.md,.csv,.xml,.html,.css,.json
Images
- Common:
.jpg,.jpeg,.png,.gif,.bmp,.webp - Vector:
.svg - Icon:
.ico
Media
- Video:
.mp4,.mkv,.webm,.avi,.mov,.wmv,.flv - Audio:
.mp3,.aac,.wav,.ogg,.midi,.flac
Development
- Source Code:
.js,.ts,.java,.cpp,.c,.py,.php,.rb,.go,.swift,.kt
Archives
- Compressed:
.zip,.rar,.7z,.tar,.gz
Other
- E-books:
.epub - Fonts:
.ttf,.otf,.woff,.woff2 - Calendar:
.ics - Executables:
.apk,.exe,.dmg,.iso
🔧 Advanced Usage
Error Handling
import { FileOpener } from '@datacomvn/file-opener';
const openFileWithErrorHandling = (filePath: string) => {
try {
const success = FileOpener.open(filePath);
if (!success) {
// Handle various failure scenarios
console.error('Failed to open file. Possible reasons:');
console.error('- File does not exist');
console.error('- No application available to handle this file type');
console.error('- Insufficient permissions');
console.error('- File is corrupted or invalid');
}
return success;
} catch (error) {
console.error('Unexpected error:', error);
return false;
}
};File Validation
import { FileOpener } from '@datacomvn/file-opener';
import RNFS from 'react-native-fs';
const openFileWithValidation = async (filePath: string) => {
try {
// Check if file exists
const exists = await RNFS.exists(filePath);
if (!exists) {
throw new Error('File does not exist');
}
// Get file info
const stat = await RNFS.stat(filePath);
console.log('File size:', stat.size, 'bytes');
console.log('Modified:', new Date(stat.mtime));
// Open the file
const success = FileOpener.open(filePath);
if (success) {
console.log('File opened successfully!');
} else {
console.error('Failed to open file');
}
return success;
} catch (error) {
console.error('Error:', error.message);
return false;
}
};🎯 Platform-Specific Behavior
iOS
- Uses the native QuickLook framework
- Provides built-in preview functionality
- Supports all formats that QuickLook can handle
- Automatic file type detection
Android
- Uses Intent.ACTION_VIEW with proper MIME type detection
- Relies on installed applications to handle specific file types
- Automatically grants temporary read permissions
- Falls back to generic handlers when specific apps aren't available
⚡ Performance
This library is built with Nitro Modules, which provides:
- Zero Bridge Calls: Direct native method invocation
- Type Safety: Full TypeScript support with native type validation
- Memory Efficiency: Minimal JavaScript ↔ Native data transfer
- Synchronous APIs: No async overhead for simple operations
🔍 Troubleshooting
Common Issues
File not opening on Android
// Ensure you have the FileProvider configured in AndroidManifest.xml
// and the file_paths.xml resource file createdPermission denied errors
// Make sure your app has the necessary permissions to access the file
// and that the file is in an accessible locationNo application found
// This happens when no app can handle the file type
// Consider providing a fallback or user guidance🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
- Clone the repository
- Install dependencies:
yarn install - Run the example app:
yarn example iosoryarn example android
Running Tests
# Run type checking
yarn typecheck
# Run linting
yarn lint
# Run tests
yarn test📋 Requirements
- React Native >= 0.70.0
- iOS >= 12.0
- Android >= API 21 (Android 5.0)
- react-native-nitro-modules >= 0.26.2
📄 License
MIT © Datacom Vietnam
🏢 About Datacom Vietnam
This library is developed and maintained by Datacom Vietnam, a leading technology company specializing in innovative mobile and web solutions.
Made with ❤️ by Datacom Vietnam
