[node.js] node:path

2025. 11. 19. 17:22·node.js

path module

path 모듈은 파일과 디렉터리 경로 작업을 위한 유틸리티를 제공합니다.

 

path 모듈은 node.js가 실행되는 운영체제에 따라 기본 동작이 달라집니다.

예를 들어, Windows 운영체제에서 path 모듈은 Windows 스타일 경로가 사용되고 있다고 가정합니다.

 

따라서 path.basename()의 실행 결과는 POSIX와 WIndows에서 다르게 나타납니다.

POSIX

path.basename('C:\\temp\\myfile.html');
// Returns: 'C:\\temp\\myfile.html'

Windows

path.basename('C:\\temp\\myfile.html');
// Returns: 'myfile.html'

 

모든 운영 체제에서 Windows 파일 경로를 사용할 때 일관된 결과를 얻으려면 path.win32를 사욥하면 됩니다.

path.win32.basename('C:\\temp\\myfile.html');
// Returns: 'myfile.html'

 

 

모든 운영 체제에서 POSIX 파일 경로를 사용할 때 일관된 결과를 얻으려면 path.posix를 사용하면 됩니다.

path.posix.basename('/tmp/myfile.html');
// Returns: 'myfile.html'

 

메서드

path.basename(path[, suffix])

path의 마지막 부분을 반환합니다.

path.basename('/foo/bar/baz/asdf/quux.html');
// Returns: 'quux.html'

 

suffix로 확장자를 주면 확장자를 제외한 부분만 반환합니다.

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

 

path.dirname(path)

path의 디렉터리를 반환합니다.

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

 

path.extname(path)

path의 확장자를 가져옵니다.

마지막으로 나타난 '.'을 기준으로 가져옵니다.

path.extname('index.html');
// Returns: '.html'

path.extname('index.coffee.md');
// Returns: '.md'

path.extname('index.');
// Returns: '.'

path.extname('index');
// Returns: ''

path.extname('.index');
// Returns: ''

path.extname('.index.md');
// Returns: '.md'

path.format(pathObject)

pathObject로부터 pathString을 생성합니다. 

path.parse()와 반대의 동작을 수행합니다.

- dir : string
- root : string
- base : string
- name : string
- ext : string
// If `dir`, `root` and `base` are provided,
// `${dir}${path.sep}${base}`
// will be returned. `root` is ignored.
path.format({
  root: '/ignored',
  dir: '/home/user/dir',
  base: 'file.txt',
});
// Returns: '/home/user/dir/file.txt'

 

path.matchesGlob(path, pattern)

path가 pattern과 일치하는지 확인합니다.

path.matchesGlob('/foo/bar', '/foo/*'); // true
path.matchesGlob('/foo/bar*', 'foo/bird'); // false

 

path.isAbsolute(path)

path가 절대 경로인지 확인합니다.

path.isAbsolute('/foo/bar');   // true
path.isAbsolute('/baz/..');    // true
path.isAbsolute('/baz/../..'); // true
path.isAbsolute('qux/');       // false
path.isAbsolute('.');          // false

 

path.join([...paths])

플랫폼별(Windows, POSIX) 구분자를 사용하여 주어진 모든 경로 segment를 연결한 후, 절대 경로를 반환합니다.

길이가 0인 경로 segment를 넣으면 무시되고 '.'을 반환합니다.

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

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

 

path.normalize(path)

'..'과 '.'등 주어진 경로를 정규화합니다.

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

 

path.parse(path)

path를 파싱 하여 다음 프로퍼티를 가지고 있는 object를 생성합니다.

- dir : string
- root : string
- base : string
- name : string
- ext : string
path.parse('/home/user/dir/file.txt');
// Returns:
// { root: '/',
//   dir: '/home/user/dir',
//   base: 'file.txt',
//   ext: '.txt',
//   name: 'file' }

 

path.relative(from, to)

current working directory를 기준으로 from에서 to로 가는 상대경로를 반환합니다.

from과 to가 같은 경우, 길이가 0인 문자열을 반환합니다.

path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
// Returns: '../../impl/bbb'

 

path.resolve([...paths])

일련의 path를 절대 경로로 변환합니다.

 

오른쪽에서 왼쪽처리하며 , 절대 경로가 생성될 때까지 path를 계속 붙입니다.

예를 들어, 경로 세그먼트 시퀀스: /foo, /bar, baz가 주어졌을 때, path.resolve('/foo', '/bar', 'baz')를 호출하면 /bar/baz를 반환합니다. 'baz'는 절대 경로가 아니지만 '/bar' + '/' + 'baz'는 절대 경로이기 때문입니다.

 

만약 절대 경로를 만들 수 없으면 current working directory의 path를 반환합니다.

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.delimiter

플랫폼별 경로 구분자를 제공합니다.

  • ; for Windows
  • : for POSIX

POSIX

console.log(process.env.PATH);
// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'

process.env.PATH.split(path.delimiter);
// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']

 

Windows

console.log(process.env.PATH);
// Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'

process.env.PATH.split(path.delimiter);
// Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']

 

path.posix

path 메서드의 POSIX 특정 구현에 대한 접근을 제공합니다.

path.sep

플랫폼별 경로 세그먼트 구분자를 제공합니다:

 

path.win32

path 메서드의 Windows 전용 구현체에 대한 접근을 제공합니다.

참고자료

https://nodejs.org/api/path.html#pathdelimiter

 

Path | Node.js v25.2.1 Documentation

Path# Source Code: lib/path.js The node:path module provides utilities for working with file and directory paths. It can be accessed using: const path = require('node:path');import path from 'node:path';copy Windows vs. POSIX# The default operation of the

nodejs.org

 

'node.js' 카테고리의 다른 글

[node.js] Buffer 란?  (0) 2025.11.21
[node.js] node:fs  (0) 2025.11.19
'node.js' 카테고리의 다른 글
  • [node.js] Buffer 란?
  • [node.js] node:fs
월월월월
월월월월
  • 월월월월
    Bobostown
    월월월월
  • 전체
    오늘
    어제
    • 분류 전체보기 (43)
      • 개발 (4)
      • 사이드 프로젝트 (1)
        • interview-lab (1)
        • Loft (0)
      • Claude (1)
      • React (5)
        • React Router (1)
        • Interactive (2)
      • Javascript (1)
      • node.js (3)
      • npm (3)
      • Nest.js (0)
      • Web (5)
        • Web API (4)
      • TDD (2)
        • Jest (0)
      • TroubleShooting (1)
      • Rust (1)
      • Bash (1)
      • 보안 (1)
      • 일상 (4)
      • 여행 (5)
      • 우아한 테크코스 8기 프리코스 (5)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    nofitication
    보홀
    오픈미션
    private package
    node.js
    peer dependency
    Web API
    webbase line
    motion
    devfest 2025
    package.json
    runzipper
    json-schema
    오실리에이터
    react
    LZ77
    framer motion
    npm
    Media Capture and Streams API
    VITE
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
월월월월
[node.js] node:path
상단으로

티스토리툴바