node fs(File System) 모듈

GABMIN KIM·2022년 1월 21일
0

node.js

목록 보기
1/6
post-thumbnail

fs 모듈

파일 시스템에 접근하는 모듈이다.

  • 파일/폴더 생성, 삭제, 읽기, 쓰기 기능 수행
  • 웹 브라우저에서는 제한적이었으나 노드는 권한을 가지고 있다.

호출

const fs = require('fs')

메서드

메서드 링크 : https://nodejs.org/api/fs.html

불러오기

  • 불러오기 메서드
fs.readFile(filename, callback)
//예시
fs.readFile('./example.txt', (err, data) => {
  if (err) {
    throw err;
  }
  console.log(data); // 컴퓨터 언어인 진법으로 데이터가 넘어온다
  console.log(data.toString()); // tostring으로 바꿔줘야한다. 

fs는 프로미스를 지원해서 사용가능하다.

const fs = require('fs').promises;

fs.readFile('./example.txt')
	.then(() => {
  		console.log(data);
  		console.log(data.toString());
	})
	.catch((err) => {
  		throw err;
	});	

작성하기

  • 작성하기 메서드
fs.writeFile(filename, data, callback)
//예시
const fs = require('fs').promises;

fs.writeFile('./example.txt', '테스트 입니다!')
	.then(() => {
  		
	})
	.catch((err) => {
  		throw err;
	});	

출처:
https://www.youtube.com/watch?v=KYxWWcZ2faI&list=PLcqDmjxt30RuRk0gcFwT_s7nexAYRF2_I&index=27

profile
목표를 성취하는 개발자가 되겠습니다.

0개의 댓글