Hello Friends 👋,
Welcome To Infinitbility! ❤️
This tutorial will help to get file details like file name, file type, file created date, file last modified date, and file size in react native with example. Here we use react-native-fs package ( https://github.com/itinance/react-native-fs ) to check file details.
Introduction
React Native FS provide stat()
function to get file details and will return Promise with file details of name, path, ctime, mtime, size, and mode.
react native fs stat()
function using syntax and response example.
stat(filepath: string): Promise<StatResult>
- react native fs
stat()
function response.
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: string; // 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?
};
Installation
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
Link react-native-fs
npx react-native link react-native-fs
React Native FS stat()
example
For stat()
example, we have pick path on device file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20210828-135547.png
and print detais got from stat()
. stat()
not return file thats ehy we use regex to show file name. check below example code and Output image.
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
SafeAreaView,
} from 'react-native';
import { stat } from 'react-native-fs';
class App extends Component {
constructor(props) {
super(props);
this.state = {
fileDetails: {},
fileName: ""
}
}
componentDidMount(){
this.fetchFileDetail();
}
fetchFileDetail = async () => {
const filePath = "file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20210828-135547.png";
var filename = filePath.replace(/^.*[\\\/]/, '')
const statResult = await stat(filePath);
console.log(statResult);
this.setState({fileDetails: statResult, filename: filename})
}
render() {
const { fileDetails, filename } = this.state;
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.container}>
<Text>File details</Text>
<Text>Ctime: {`${fileDetails.ctime}`}</Text>
<Text>mode: {`${fileDetails.mode}`}</Text>
<Text>mtime: {`${fileDetails.mtime}`}</Text>
<Text>originalFilepath: {`${fileDetails.originalFilepath}`}</Text>
<Text>path: {`${fileDetails.path}`}</Text>
<Text>size: {`${fileDetails.size}`}</Text>
<Text>file name: {`${filename}`}</Text>
</View>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
marginTop: 20,
backgroundColor: '#ffffff',
},
});
export default App;
Output
Thanks for Reading…