본문 바로가기
기타

[NodeJS] path.join 과 path.resolve 차이 📋 / path.join이란? / path.resolve란?

by 서상혁 2020. 1. 30.

Path.join

path.join([...paths])  * ...paths 인자들은 항상 string이어야 합니다.

 

경로들을 string 으로 받아 합쳐줍니다.

 

예시) 

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'

path.join('foo', {}, 'bar');
// Throws 'TypeError: Path must be a string. Received {}'

(Node.js 홈페이지 제공)

 

첫번째 예시의 경우, 하나하나 stirng들을 경로라고 생각해서 /로 구분지어 새로운 경로를 만들어냅니다.

quux가 포함되지 않는 이유는 '..' 가 상위 폴더 를 가리키기 때문❗

 

Path.resolve

path.resolve([...paths])  * ...paths 인자들은 항상 string이어야 합니다.

 

path.resolve 도 path.join과 유사하게 경로들을 묶어 새로운 경로를 반환합니다.

 

예시) 

path.resolve('/foo/bar', './baz');
// Returns: '/foo/bar/baz'

path.resolve('/foo/bar', '/tmp/file/');
// Returns: '/tmp/file'

path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
// If the current working directory is /home/myself/node,
// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'

 

예시를 보시면 path.join과는 다른점들이 보입니다.

 

resolve만의 차이점

  • 오른쪽에서 왼쪽으로 경로들을 읽습니다.

  • '/폴더명' 을 만나면 절대경로로 인식해서 그 경로를 바로 반환합니다.

  • 따라서 경로를 합치기위해서는 상대경로인 './폴더명' 으로 확실하게 구분해줘야합니다.

쉽게 말하자면 path.resolve는 오른쪽에서 왼쪽으로 읽으며 path.join 과는 다르게 상대경로와 절대경로를 인식하여 구분합니다!

 

728x90

댓글