[SeSACx코딩온] 모듈(Module) 종류
모듈(Module) 종류
1. path 모듈
(1) 주요 메서드
path.join()
: 여러 인자를 넣어 하나의 경로로 합쳐줍니다.path.resolve()
: 절대 경로를 반환하며,path.join()
과 비슷하지만 차이점이 있습니다.path.parse()
: 파일 경로를root
,dir
,base
,ext
,name
으로 구분합니다.path.format()
:path.parse()
로 구분한 객체를 다시 파일 경로로 합칩니다.path.basename()
: 파일의 기본 이름을 반환합니다.path.extname()
: 파일의 확장자를 반환합니다.
참고
path.join()와 path.resolve()은 둘 다 경로를 조합하는 데 사용되지만, 동작 방식에는 차이가 있습니다.
1) path.join(): 인자로 받은 경로들을 결합하여 상대 경로를 생성합니다. 인자 중에 /로 시작하는 절대 경로가 없으면 모든 인자가 결합된 상대 경로를 반환합니다.
2) path.resolve(): 인자로 받은 경로를 결합하여 절대 경로를 반환합니다. 인자 중 절대 경로가 포함되어 있으면 그 절대 경로를 기준으로 나머지 인자를 결합합니다. 그렇지 않으면 현재 작업 디렉토리를 기준으로 경로를 계산합니다.
// 현재 작업 디렉토리가 /home/user인 경우,
path.join('first', 'second', 'third') => 'first/second/third' (상대 경로)
path.resolve('first', 'second', 'third') => '/home/user/first/second/third' (절대 경로)
path.join('/first', 'second', 'third') => '/first/second/third' (절대 경로)
path.resolve('/first', 'second', 'third') => '/first/second/third' (절대 경로)
path.join('first', '/second', 'third') => '/second/third' (절대 경로)
path.resolve('first', '/second', 'third') => '/second/third' (절대 경로)
// 중간에 절대 경로가 등장하면 그 이전 인자는 무시.
const path = require('path');
console.log(path.join('a', 'b', 'index.html')); // 'a/b/index.html'
console.log(path.resolve('a', 'b', 'index.html')); // 절대 경로를 반환
console.log(path.parse('/home/user/dir/file.txt')); // { root: '/', dir: '/home/user/dir', base: 'file.txt', ext: '.txt', name: 'file' }
console.log(path.extname('/home/user/dir/file.txt')); // '.txt'
console.log(path.basename('/home/user/dir/file.txt')); // 'file.txt'
2. os 모듈
(1) 주요 메서드
os.totalmem()
: 시스템의 총 메모리 양을 반환합니다.os.freemem()
: 시스템에서 사용 가능한 메모리 양을 반환합니다.os.cpus()
: CPU 코어 정보를 배열 형태로 반환합니다.os.homedir()
: 사용자의 홈 디렉토리 경로를 반환합니다.
const os = require('os');
let totalMemory = os.totalmem();
let freeMemory = os.freemem();
console.log(`Total Memory: ${totalMemory}`);
console.log(`Free Memory: ${freeMemory}`);
3. fs 모듈
(1) 주요 메서드
fs.mkdir()
: 디렉토리를 생성합니다.fs.rmdir()
: 디렉토리를 삭제합니다.fs.readdir()
: 디렉토리의 내용을 읽어옵니다.fs.writeFile()
: 파일을 생성하고 내용을 씁니다.fs.appendFile()
: 파일에 내용을 추가합니다.fs.readFile()
: 파일의 내용을 비동기적으로 읽어옵니다.fs.readFileSync()
: 파일의 내용을 동기적으로 읽어옵니다.fs.unlink()
: 파일을 삭제합니다.fs.rename()
: 파일의 이름을 변경합니다.
(2) 디렉토리 생성 및 삭제
const fs = require('fs');
const path = require('path');
// 디렉토리 생성
fs.mkdir(path.join(__dirname, 'test'), (err) => {
if (err) {
return console.error(err);
}
console.log('디렉토리 생성 완료');
});
// 디렉토리 삭제
fs.rmdir(path.join(__dirname, 'test'), (err) => {
if (err) {
return console.error(err);
}
console.log('디렉토리 삭제 완료');
});
(3) 파일 생성 및 읽기
// 파일 생성
fs.writeFile('mynewfile1.txt', 'Hello world', (err) => {
if (err) throw err;
console.log('파일이 생성됨.');
});
// 파일 읽기 (비동기)
fs.readFile('./input.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log(data);
console.log('파일 읽기 완료');
});
// 파일 읽기 (동기)
const data = fs.readFileSync('./input.txt', 'utf-8');
console.log(data);
console.log('파일 읽기 완료');
참고 1) 동기 방식 : 함수가 호출되면 파일 작업이 완료될 때까지 코드 실행이 다음 코드가 실행되기 전에 파일 작업이 끝날 때까지 기다립니다. 파일 작업이 오래 걸릴 경우 전체 애플리케이션이 멈출 수 있습니다.
2) 비동기 방식 : 파일 작업이 백그라운드에서 진행되고, 작업이 완료되면 콜백 함수가 호출됩니다. 코드 실행은 파일 작업이 끝날 때까지 기다리지 않으며, 다른 작업을 계속 수행할 수 있습니다. 이 방식은 성능에 유리하지만, 콜백 관련 문제나 복잡한 코드 구조로 문제를 유발할 수 있습니다.
(4) 파일 삭제 및 이름 변경
// 파일 삭제
fs.unlink('mynewfile2.txt', (err) => {
if (err) throw err;
console.log('파일 삭제 완료');
});
// 파일 이름 변경
fs.rename('mynewfile1.txt', 'renamefile1.txt', (err) => {
if (err) throw err;
console.log('파일 이름 변경 완료');
});