[Node.js] __dirname / process.cwd()
https://www.digitalocean.com/community/tutorials/nodejs-how-to-use__dirname
How To Use __dirname in Node.js | DigitalOcean
www.digitalocean.com
1. __dirname 이 뭔가?
" __dirname은 현재 실행 중인 파일이 포함된 디렉토리의 절대 경로를 알려주는 환경 변수입니다."
-> 쉽게 말해 절대 경로다
>> 요런~ 파일 경로를 가진 프로젝트가 있다 치자.
프로젝트의 최상위 폴더는 dirname-example 이 되고 그 하위로 쭉쭉있다.
controller.js 파일은 src/api/ 아래에 있다.
여기에서 콘솔을 찍어보면
console.log(__dirname) // "/Users/Sam/dirname-example/src/api" -> 얘는 절대 경로를 보여주고
console.log(process.cwd()) // "/Users/Sam/dirname-example" -> process.cwd() 얘는 그냥 프로젝트의 경로를 보여준다
hello.js 파일은 conjobs 폴더 아래에 있다
여기에서 콘솔 찍으면?
console.log(__dirname) // "/Users/Sam/dirname-example/cronjobs" -> 절대경로
console.log(process.cwd()) // "/Users/Sam/dirname-example" -> 프로젝트 경로~
이렇게 나온다.
2. __dirname 사용법
path.jon() 이랑 같이 조합해서 마니 쓴다.
예를 들어 새로운 경로를 만들거나, 특정 경로를 어떤 용도로 지정하고 싶을때.
(1) 파일 지정하기
> index.js 에서
express.static(path.join(__dirname, '/public'));
라고 써주면 public 폴더 (정적 파일 담은 디렉토리)를 express.static의 대상 디렉토리로 "지정" 할 수 있음.
(2) 디렉토리 지정 및 생성하기
> index.js 에서
const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, '/pictures');
fs.mkdirSync(dirPath);
path.jdoin으로 경로를 지정해준뒤,
fs.mkdirSync() 로 경로를 생성해준다.
(3) 파일 생성하기
> index.js 에서
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, '/pictures');
fs.openSync(filePath, 'hello.jpeg');
path.join에 첫번째 인자로 __dirname , 두번째 인자로 추가하고 싶은 파일을 적어준 뒤 (-> 이부분 잘 이해 안됨.
문서에서는 추가해주고싶은 '파일'을 두번째 인자로 넣는다고 나와있는데, 의미상 파일을 추가할 폴더명을 넣어주는게 아닌지..?)
fs.openSync() 를 조합해준다. fs.openSync()는 첫번째 인자로 경로 , 두번째 인자로 추가해줄 파일을 넣는다.
openSync() 메소드는 디렉토리에 파일이 없는 경우, 파일을 추가해준다.
맨날 봐도 맨날 까먹어서 다시 적었음