nodejs의 file system (node:fs)
node:fs 모듈은 표준 POSIX 함수 기반으로 파일 시스템과 상호작용을 가능하게 한다.
API는 크게 3가지로 나뉘어진다. Promises API, Callback API, Synchronous API.
promise기반 api를 사용할 때:
import * as fs from 'node:fs/promises';
callback 이나 sync api를 사용할 때:
import * as fs from 'node:fs';
Promise 예제
promise기반 작업은 비동기 작업이 완료되었을 때 promise가 반환된다.
import { unlink } from 'node:fs/promises';
try {
await unlink('/tmp/hello');
console.log('successfully deleted /tmp/hello');
} catch (error) {
console.error('there was an error:', error.message);
}
Callback 예제
callback형식은 마지막 매개변수로 콜백 함수를 받고, 비동기적으로 작업을 한다. 콜백의 매개변수는 메소드에 의해 결정되지만, 첫번째 매개변수는 항상 예외를 위한 것이다. 작업이 성공적으로 완료되었다면, 첫번째 매개변수는 null 또는 undefined이다.
import { unlink } from 'node:fs';
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
Synchronous 예제
동기식 API는 작업이 완료될 때까지 nodejs의 event loop와 추가 javascript 실행을 막는다. 예외는 즉시 던져지고 try...catch로 다루거나 bubble up(bubble up이 뭘까?) 할 수 있다.
import { unlinkSync } from 'node:fs';
try {
unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
} catch (err) {
// handle the error
}
우리는 여기서 자주 사용되는 몇가지 callback과 synchronous를 알아보자.
이름 | 설명 |
fs.readFile(path[, options], callback) | 비동기적 파일 읽기 |
fs.readFileSync(path[, options]) | 동기적 파일 읽기 |
fs.writeFile(file, data[, options], callback) | 비동기적 파일 쓰기 |
fs.writeFileSync(file, data[, options]) | 동기적 파일 쓰기 |
fs.appendFile(path, data[, options], callback) | 비동기적 파일 덧붙이기 |
fs.appendFileSync(path, data[, options]) | 동기적 파일 덧붙이기 |
fs.readFile(path[, options], callback)
path 파일 이름 또는 파일 디스크립터
options
- encoding 기본값: null
- flag 기본값: 'r'
- signal 진행중인 파일 읽기를 중단시키는걸 허용한다(?)
callback
- err
- data
fs.readFileSync(path[, options])
path 파일 이름 또는 파일 디스크립터
options
- encoding 기본값: null
- flag 기본값: 'r'
return <String> | <Buffer>
fs.writeFile(file, data[, options], callback)
file 파일 이름 또는 파일 디스크립터
data <stirng> | <Buffer> | <TypedArray> | <DataView>
options
- encoding 기본값: 'utf8'
- mode 기본값:0o666
- flag 기본값: 'w'
- signal 진행중인 파일 읽기를 중단시키는걸 허용한다(?)
callback
- err
fs.writeFileSync(file, data[, options])
file 파일 이름 또는 파일 디스크립터
data <stirng> | <Buffer> | <TypedArray> | <DataView>
options
- encoding 기본값: 'utf8'
- mode 기본값:0o666
- flag 기본값: 'w'
return undefined
fs.appendFile(path, data[, options], callback)
path 파일 이름 또는 파일 디스크립터
data <stirng> | <Buffer>
options
- encoding 기본값: 'utf8'
- mode 기본값:0o666
- flag 기본값: 'a'
callback
- err
fs.appendFileSync(path, data[, options])
path 파일 이름 또는 파일 디스크립터
data <stirng> | <Buffer>
options
- encoding 기본값: 'utf8'
- mode 기본값:0o666
- flag 기본값: 'a'
참고: https://nodejs.org/api/fs.html