fs module
node.js에서 파일 시스템에 접근할 수 있는 방법은 2가지입니다.
- promise-based API인 node:fs/promises
- callback 및 sync API인 node:fs
모든 파일 시스템 작업은 동기식, 콜백 방식, 프로미스 기반 형태로 제공되며, CommonJS 구문과 ES6 모듈(ESM)을 모두 사용하여 접근할 수 있습니다.
Promise Example
node:fs/promises 모듈을 사용하여 비동기 작업을 처리할 때는 다음과 같이 사용할 수 있습니다.
const { unlink } = require('node:fs/promises');
(async function(path) {
try {
await unlink(path);
console.log(`successfully deleted ${path}`);
} catch (error) {
console.error('there was an error:', error.message);
}
})('/tmp/hello');
Callback Example
node:fs 모듈을 사용하여 콜백으로 비동기 작업을 처리할 때는 다음과 같이 사용할 수 있습니다.
const { unlink } = require('node:fs');
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
자주 사용되는 메서드
node:fs의 메서드 중에서도 자주 사용되는 메서드를 정리해 보겠습니다.
fs.readFileSync(path[, options])
파일을 동기적으로 읽습니다.
# options
- encoding : encoding이 주어지면 readFileSync는 string을 반환하고, 없다면 buffer를 반환합니다.
fs.writeFileSync(file, data[, options])
파일을 동기적으로 작성합니다.
- encoding : string
- mode : interger
- flag : string
- flush : boolean, 데이터가 성공적으로 파일에 작성되면 fs.fsyncSync를 사용하여 데이터를 flush 합니다.
fs.appendFileSync(path, data[, options])
파일의 끝에 data를 추가합니다.
- encoding : string
- mode : interger
- flag : string
- flush : boolean, 데이터가 성공적으로 파일에 작성되면 fs.fsyncSync를 사용하여 데이터를 flush 합니다.
fs.existsSync(path)
해당 경로의 path가 실제로 존재하는지 확인합니다.
fs.fstatSync(fd[, options])
파일 정보를 확인할 수 있는 fs.Stats를 반환합니다.
자주 사용되는 클래스
클래스는 메서드가 많아 해당 클래스의 공식문서를 링크로 달아놓겠습니다.
fs.Dir
File system | Node.js v25.2.1 Documentation
File system# Source Code: lib/fs.js The node:fs module enables interacting with the file system in a way modeled on standard POSIX functions. To use the promise-based APIs: import * as fs from 'node:fs/promises';const fs = require('node:fs/promises');copy
nodejs.org
디렉토리 스트림을 나타내는 클래스입니다.
fs.Dirent
File system | Node.js v25.2.1 Documentation
File system# Source Code: lib/fs.js The node:fs module enables interacting with the file system in a way modeled on standard POSIX functions. To use the promise-based APIs: import * as fs from 'node:fs/promises';const fs = require('node:fs/promises');copy
nodejs.org
디렉터리 엔트리 정보로, 디렉터리 내의 파일 또는 하위 디렉터리일 수 있습니다.
디렉토리 목록을 조회할 때 사용합니다.
fs.Stats
File system | Node.js v25.2.1 Documentation
File system# Source Code: lib/fs.js The node:fs module enables interacting with the file system in a way modeled on standard POSIX functions. To use the promise-based APIs: import * as fs from 'node:fs/promises';const fs = require('node:fs/promises');copy
nodejs.org
파일/디렉터리 정보를 담는 객체입니다.
파일/디렉터리의 상세 정보를 담고 있습니다.
'node.js' 카테고리의 다른 글
| [node.js] Buffer 란? (0) | 2025.11.21 |
|---|---|
| [node.js] node:path (1) | 2025.11.19 |