fs 모듈은 파일 시스템에 접근하는 모듈임.
읽기
저를 읽어주세요.
const fs = require('fs');
fs.readFile('/readme.txt', (err, data) => {
if (err) {
throw err;
}
console.log(data);
console.log(data.toString());
});

- readFile의 결과물은 버퍼라는 형식으로 제공됨.
쓰기
const fs = require('fs');
fs.writeFile('./writeme.txt', '글이 입력됩니다.', (err) => {
if (err) {
throw err;
}
fs.readFile('./writeme.txt', (err, data) => {
if (err) {
throw err;
}
console.log(data.toString());
});
});
- writeFile() 메소드에 생성될 파일의 경로와 내용을 입력
동기 메서드와 비동기 메서드
- setTimeout 같은 타이머와 process.nextTick 외에도, 노드는 대부분의 메서드를 비동기 방식으로 처리
- 특히 fs 모듈이 그러한 메서드를 많이 가지고 있음
- [ 예 시 ]




순서대로 출력하고 싶을 때,

- 위와 같은 코드는 치명적인 단점이 있음.
- 그 단점은 이전 작업이 완료되어야 다음 작업을 진행할 수 있음
- 즉, 백그라운드가 작업하는 동안 메인 스레드는 멈춤(대기상태)
비동기 + 순서대로

- 콜백 지옥이 펼쳐지지만 적어도 순서가 어긋나지는 않음
- 그래도 Promise나 async/await으로 어느 정도 해결 가능
$ node asyncOrder
시작
끝
1번 저를..
2번 저를..
3번 저를..
버퍼와 스트림 이해하기
- data를 읽어서 toString()으로 변환을 해야함
- 이유는 data가 버퍼이기 때문
- 파일을 읽거나 쓰는 방식에는 크게 두 가지 방식이 있음.
- 버퍼를 이용하는 방식과 스트림을 이용하는 방식
- 버퍼링과 스트리밍이라는 용어를 알고있을거임!!
- 버퍼링 : 영상을 재생할 수 있을 때까지 데이터를 모으는 동작
- 스트리밍 : 방송인의 컴퓨터에서 시청자의 컴퓨터로 영상 데이터를 조금씩 전송하는 동작
- 노드는 파일을 읽을 때 메모리에 파일 크기만큼 공간을 마련해두며, 파일 데이터를 메모리에 저장한 뒤 사용자가 조작할 수 있도록 해줌 ( 이 데이터가 버퍼임 )
- 버퍼를 다루는 클래스가 Buffer 임


- 근데, 이러면 매번 전체 용량을 버퍼로 처리해야 하기에 안좋음
- 그래서 여러 번에 나눠서 보내는 방식이 등작했고, 그게 바로 스트림임



- createReadStream()으로 읽기 스트림을 만들어주고, 첫 번째 인자로 읽을 파일의 경로, 두 번째 인자는 옵션 객체인데, highWaterMark라는 옵션은 버퍼의 크기(바이트 단위)를 정할 수 있는 옵션. 기본값은 64KB 임.
쓰기 스트림

읽은 스트림을 받아 파일을 쓰는 스트림
const fs = require('fs');
const readStream = fs.createReadStream('readme.txt');
const writeStream = fs.createWriteStream('writeme.txt');
readStream.pipe(writeStream);
읽고 압축

기타 fs 메서드
- fs.access(경로, 옵션, 콜백) : 폴더나 파일에 접근할 수 있는지를 체크
- fs.mkdir(경로, 콜백) : 폴더를 만드는 메서드. 이미 폴더가 있다면 에러
- fs.open(경로, 옵션, 콜백) : 파일의 아이디(fd 변수)를 가져오는 메서드
- fs.rename(기존 경로, 새 경로, 콜백) : 파일의 이름을 바꾸는 메서드
폴더 내용 확인 및 삭제

- fs.readdir(경로, 콜백) : 폴더 안의 내용물을 확인. 배열안에 내부 파일과 폴더명이 나옴
- fs.unlink(경로, 콜백) : 파일을 지울 수 있음. 파일이 없다면 에러
- fs.rmdir(경로, 콜백) : 폴더를 지울 수 있음. 폴더 안에 파일이 있다면 에러
파일 복사

