[개발지식] 알아두면 좋은 file system API

Hyo Kyun Lee·2021년 11월 12일
0

개발지식

목록 보기
14/43

1. 개요

기존에 작성하였던 filesystem과 더불어, 알아두면 유용하게 사용할 수 있는 fs API를 알아둔다.

2. fs module

const fs = require('fs')

내부적인 file system에 접근하여 파일을 CRUD할 수 있는 API를 제공한다.

2-1. file read

file의 내용을 읽는다.

fs.readFile('file path', 'encoding type', (err, data))

const fs = require('fs');

let path = './localstorage/created'

async function fileread(fileName){
    await fs.readFile(`${path}/${fileName}.txt`, 'utf-8', (err, data)=>{
        console.log(data)
    })
    
}
  • read할 파일의 경로, 파일형식을 기입하여 준다.
  • read완료후 읽은 data를 return받는다.

※ null일 경우 경로 및 err/data arguments 확인.

2-2. file create

file을 생성한다.

fs.writeFile('file path', 'file content', (err))

const fs = require('fs');

let path = './localstorage/created'

async function fileload(fileName){
    fs.writeFile(`${path}/${fileName}.txt`, 'content', (err)=>{
        //console.log('what happened?');
    })
}

module.exports = fileload;
  • 파일을 create할 경로와 내용을 기입하여 준다.
  • create 실패하였을 경우의 err인자를 유의한다.

2-3. file read

file을 삭제한다.

fs.delete('file path')

const fs = require('fs');

let path = './localstorage/created'

async function filedelete(fileName){
    fs.unlink(`${path}/${fileName}.txt`, (err)=>{
        //console.log('what happened?');
    })
}

module.exports = filedelete;
  • 삭제할 file의 경로를 기입하여 준다.

3. 참고

일전에 사용하였던 window.showOpenFilePicker()는 별도의 event 발생이 생기거나, HTML에서 작성(window 객체)하는 등 제약사항이 다소 많을 수 있다.

상황에 맞게 적절한 방식의 file system API/method를 사용하도록 한다.

4. 참조링크

fs module / fs.readFile()
https://jamong-icetea.tistory.com/132

fs를 통해 사용가능한 API
https://dydals5678.tistory.com/96

multer (*)
https://www.a-mean-blog.com/ko/blog/%EB%8B%A8%ED%8E%B8%EA%B0%95%EC%A2%8C/_/Node-JS-Multer%EB%A1%9C-%ED%8C%8C%EC%9D%BC-%EC%97%85%EB%A1%9C%EB%93%9C

stackflow에서 참고하였던 fs 관련 오류 / 명세
https://stackoverflow.com/questions/10015877/node-js-fs-readfile-not-working-in-windows
https://stackoverflow.com/questions/5315138/node-js-remove-file

0개의 댓글