React Native - 파일 시스템
RN 개발을 하다보면, 파일 시스템(filesystem)을 이용하여 파일을 읽고 쓰는 경우가 생긴다. 본인은 최근에는 java와 kotlin 파일에 설정 적용차이에서 에러가 발생해 react-native-file-access 라는 라이브러리를 활용했지만, 이번 글에서는 본인도 사용했었고 파일시스템 라이브러리 중에서 가장 기본적이고 유명한 react-native-fs 사용법을 정리한다.
https://www.npmjs.com/package/react-native-fs
react-native-fs
Native filesystem access for react-native. Latest version: 2.20.0, last published: 3 years ago. Start using react-native-fs in your project by running `npm i react-native-fs`. There are 491 other projects in the npm registry using react-native-fs.
www.npmjs.com
react-native-fs
1. 파일 및 디렉토리에 대한 CRUD와 함께 이름 변경, 위치 이동, 파일 정보 조회 등에 대한 기능
2. 파일 경로 접근에 용이
3. 대용량 파일처리
4. url 을 통한 다운로드 및 업로드
5. 백그라운드 작업
1. 설치
npm install react-native-fs
#or
yarn add react-native-fs
2. 설정
android/setting.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')
}
android/app/src/main/java/com/.../MainApplication.java
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
);
}
3. 메소드 정리
아래에 정리한 메소드는 본인이 사용해보거나 자주 사용되는 메소드들이다.
이 외에 더 많은 기능들이 공식문서에 있으니 필요에 따라 찾아서 사용하면 된다.
- writeFile(filePath, contents, encoding-type?) : 파일 작성
- readFile(filePath, encoding-type?) : 파일 읽기(내용을 문자열로 반환)
- appendFile(filePath, contents, encoding-type?) : 기존 파일에 내용 추가
- write(filePath, contents, position, encoding-type?) : 파일의 특정 부분 추가 및 수정
- unlink(filePaht) : 파일 삭제
- moveFile(srcPath, destPath) : 파일 이동
- copyFile(srcPath, destPath) : 파일 복사
- mkdir(dirPath) : 디렉토리 생성
- rmdir(dirPath) : 디렉토리 삭제
- readdir(dirPath) : 디렉토리 내의 파일 및 서브 디렉토리 목록 읽기
- downloadFile(options) : 원격 서버에서 파일 다운로드
- uploadFiles(options) : 하나 이상의 파일을 서버 업로드
- stat(filePath) : 파일 또는 디렉토리 속성 조회
- exists(filePath) : 파일 존재 여부 체크
4. 파일 경로 변수
메소드와 마찬가지로 아래 외에도 더 많은 파일 경로 변수가 존재한다.
- DocumentDirectoryPath : 문서 디렉토리 경로 (클라이언트 데이터 저장을 위해)
- CachesDirectoryPath : 캐시 디렉토리 경로 (일시적 데이터 저장을 위해)
- ExternalDirectoryPath : 외부 저장소 경로