본문 바로가기
node.js

node 파일 시스템(생성, 삭제, 읽기, 쓰기 + 썸네일)

by 아구몬선생 2022. 4. 13.

Node.js의 파일 시스템 모듈은 컴퓨터에 있는 파일 시스템이 작동하게 한다. 파일의 생성, 삭제, 읽기, 쓰기 등을 수행할 수 있으며, 폴더를 생성하고 삭제한다.

파일 시스템 모듈 불러오기

파일 시스템 모듈 fs를 require로 불러서 사용

const fs = require('fs')

공식문서 : https://nodejs.org/docs/latest-v14.x/api/fs.html

 

기본 구조

fs.[함수](path, callback)
fs.[함수]Sync(path)

파일 생성 시 경로 확인 및 디렉토리가 없을 때 생성

const fs = require('fs')

const directory = "./sample/example"

// existsSync로 파일 존재 여부를 블린으로 확인
// 해당 디렉토리가 없을시 mkdir 이용해서 생성
// recursive는 여러개의 디렉터리를 동시에 생성해 주는 옵션
if(!fs.existsSync(directory)){
	fs.mkdir(directory, {recursive:true}, (err) =>{
    if(err) throw err{
    console.log(err);
}

node.js에서는 xxxxSync 라는 함수를 사용하면 callback으로 사용하지 않고 또는 promise로 변환하지 않아도 사용할 수 있어서 편하지만 비동기 방식이 아닌 동기 방식이라 코드가 블락돼서 응답이 멈출 수 있다. 또는 성능이 느려질 수 있다.

파일 생성(쓰기)

fs.writeFile([경로], [파일데이터], [인코딩])

fs.writeFile("./sample/example/image", filedata, utf-8, (err) => {
	if(err) throw err {
    	console.log(err)
    }
})

// Promise 사용

const fsp = fs.promises;

fsp.writeFile("./sample/example/image", filedata, utf-8)

파일 읽기

fs.readFile([경로], [인코딩])

fs.readFile("./sample/example/image", utf-8, (err) => {
	if(err) throw err {
    	console.log(err)
    }
}))


// Promise 사용

const fsp = fs.promises;

fsp.readFile("./sample/example/image", filedata, utf-8)

'node.js' 카테고리의 다른 글

res.send(), res.json(), res.end() 궁금해서 찾아봄  (0) 2022.04.11