[TIL] Expo File System 사용법(기본)

햄스터아저씨·2021년 7월 14일
1

설치

expo install expo-file-system

기본설정 (복붙)

1) import

import * as FileSystem from 'expo-file-system';

2) Directory Promise

다음과 같이 디렉토리가 있음을 보장하는 함수가 필요하다.

async function ensureDirExists() {
  const dir = FileSystem.documentDirectory + "myDirectory/";
  const dirInfo = await FileSystem.getInfoAsync(dir);
  if (!dirInfo.exists) {
    console.log("directory doesn't exist, creating...");
    await FileSystem.makeDirectoryAsync(dir, { intermediates: true });
  } else {
    console.log("directory alreay exists");
  }
}

이러면 Promise 로 사용할 수 있다.

ensureDirExists()
  .then(() =>
        FileSystem.~~~
  )
  .catch((e) => console.log(e));

만일 ensureDirExists() 쓰지 않고 생성/수정/삭제를 시도하다가, 디렉토리가 없으면 다음과 같은 에러를 만나게 될 것이다.

/data/user/0/host.exp.exponent/files/ExperienceData/<패키지, 앱이름>/myDirectory/myFile: open failed: ENOENT (No such file or directory)
at node_modules/react-native/Libraries/BatchedBridge/NativeModules.js:103:50 in promiseMethodWrapper
at node_modules/@unimodules/react-native-adapter/build/NativeModulesProxy.native.js:15:23 in moduleName.methodInfo.name
at node_modules/expo-file-system/build/FileSystem.js:50:17 in writeAsStringAsync
at node_modules/expo-file-system/build/FileSystem.js:46:7 in writeAsStringAsync
at node_modules/react-native/Libraries/Pressability/Pressability.js:691:17 in _performTransitionSideEffects
at node_modules/react-native/Libraries/Pressability/Pressability.js:628:6 in _receiveSignal
at node_modules/react-native/Libraries/Pressability/Pressability.js:524:8 in responderEventHandlers.onResponderRelease
at [native code]:null in forEach
at [native code]:null in callFunctionReturnFlushedQueue

쓰기

FileSystem.writeAsStringAsync()

const fileUri = FileSystem.documentDirectory + "myDirectory/myFile";
ensureDirExists()
  .then(() =>
    FileSystem.writeAsStringAsync(fileUri, "contents!")
      .then((contents) => {
        console.log("write Success");
        console.log(contents);
      })
      .catch((e) => console.log(e))
  )
  .catch((e) => console.log(e));

읽기

FileSystem.readAsStringAsync()

const fileUri = FileSystem.documentDirectory + "myDirectory/myFile";
ensureDirExists()
  .then(() =>
    FileSystem.readAsStringAsync(fileUri)
      .then((contents) => {
        console.log("Read Success");
        console.log(contents);
      })
      .catch((e) => console.log(e))
  )
  .catch((e) => console.log(e));

삭제

FileSystem.writeAsStringAsync()

const fileUri = FileSystem.documentDirectory + "myDirectory/myFile";
ensureDirExists()
  .then(() =>
    FileSystem.deleteAsync(dir)
      .then(() => {
        console.log("Delete Success");
      })
      .catch((e) => console.log(e))
  )
  .catch((e) => console.log(e));

여기까지 Expo의 FileSystem 의 생성/수정/삭제 를 알아봤다.
이 외에도 Device의 용량을 알아낼 수도 있고 여러 좋은 함수들이 있다. 실제로 FileSystem을 사용하고자 한다면 아래 문서를 반드시 읽자.

공식문서: https://docs.expo.io/versions/latest/sdk/filesystem/

profile
서버도 하고 웹도 하고 시스템이나 인프라나 네트워크나 그냥 다 함.

0개의 댓글