모듈
- 프로그램을 작은 기능 단위로 쪼개고 파일 형태로 저장해 놓은 것
- 코드를 중복해서 사용할 필요 없음
- 수정이 필요한 경우 모듈만 수정
module.exports= hello; // 할당
const hello= require("./hello"); // 사용
경로확인
console.log(`현재 모듈이 있는 폴더: ${__dirname}`);
console.log(`현재 모듈의 파일명 : ${__filename}`);
path 모듈
- 윈도우, 맥의 경로 구분자가 다르기 때문에 통일할 필요가 있다.
- 상대경로 (같은 폴더에 있을 경우 './' 부모 폴더 '../')
// path 모듈 연습하기 ( 결과 비교 파일 : 03\results\path.js)
const path= require("path");
// join
const fullPath= path.join('some', 'work', 'ex.txt');
console.log(fullPath);
// 경로만 추출 - dirname
const dir= path.dirname(fullPath);
console.log(dir);
// 파일 이름만 추출 - basename
const fn1= path.basename(__filename);
console.log(`전체경로(__filename): ${__filename}`);
console.log(fn1);
const fn2= path.basename(__filename, '.js');
console.log(fn2);
File System 모듈
// fs 모듈의 readdir 함수 연습하기 ( 결과 비교 파일 : 03\results\list-2.js)
const fs= require("fs");
fs.readdir("./", (err, files) => {
if(err){
console.log(err);
}
console.log(files);
});
// fs 모듈의 readFile 함수 연습하기 (결과 비교 파일은 03\results\read-3.js)
const fs= require("fs");
fs.readFile("./example.txt", "utf8", (err, data)=>{
if(err){
console.log(err);
}
console.log(data);
fs.writeFile("./test.txt", data, (err)=>{
if(err){
console.log(err);
}
console.log("test.txt is saved");
})
})