• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Path
2
3<!--introduced_in=v0.10.0-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/path.js -->
8
9The `node:path` module provides utilities for working with file and directory
10paths. It can be accessed using:
11
12```js
13const path = require('node:path');
14```
15
16## Windows vs. POSIX
17
18The default operation of the `node:path` module varies based on the operating
19system on which a Node.js application is running. Specifically, when running on
20a Windows operating system, the `node:path` module will assume that
21Windows-style paths are being used.
22
23So using `path.basename()` might yield different results on POSIX and Windows:
24
25On POSIX:
26
27```js
28path.basename('C:\\temp\\myfile.html');
29// Returns: 'C:\\temp\\myfile.html'
30```
31
32On Windows:
33
34```js
35path.basename('C:\\temp\\myfile.html');
36// Returns: 'myfile.html'
37```
38
39To achieve consistent results when working with Windows file paths on any
40operating system, use [`path.win32`][]:
41
42On POSIX and Windows:
43
44```js
45path.win32.basename('C:\\temp\\myfile.html');
46// Returns: 'myfile.html'
47```
48
49To achieve consistent results when working with POSIX file paths on any
50operating system, use [`path.posix`][]:
51
52On POSIX and Windows:
53
54```js
55path.posix.basename('/tmp/myfile.html');
56// Returns: 'myfile.html'
57```
58
59On Windows Node.js follows the concept of per-drive working directory.
60This behavior can be observed when using a drive path without a backslash. For
61example, `path.resolve('C:\\')` can potentially return a different result than
62`path.resolve('C:')`. For more information, see
63[this MSDN page][MSDN-Rel-Path].
64
65## `path.basename(path[, suffix])`
66
67<!-- YAML
68added: v0.1.25
69changes:
70  - version: v6.0.0
71    pr-url: https://github.com/nodejs/node/pull/5348
72    description: Passing a non-string as the `path` argument will throw now.
73-->
74
75* `path` {string}
76* `suffix` {string} An optional suffix to remove
77* Returns: {string}
78
79The `path.basename()` method returns the last portion of a `path`, similar to
80the Unix `basename` command. Trailing [directory separators][`path.sep`] are
81ignored.
82
83```js
84path.basename('/foo/bar/baz/asdf/quux.html');
85// Returns: 'quux.html'
86
87path.basename('/foo/bar/baz/asdf/quux.html', '.html');
88// Returns: 'quux'
89```
90
91Although Windows usually treats file names, including file extensions, in a
92case-insensitive manner, this function does not. For example, `C:\\foo.html` and
93`C:\\foo.HTML` refer to the same file, but `basename` treats the extension as a
94case-sensitive string:
95
96```js
97path.win32.basename('C:\\foo.html', '.html');
98// Returns: 'foo'
99
100path.win32.basename('C:\\foo.HTML', '.html');
101// Returns: 'foo.HTML'
102```
103
104A [`TypeError`][] is thrown if `path` is not a string or if `suffix` is given
105and is not a string.
106
107## `path.delimiter`
108
109<!-- YAML
110added: v0.9.3
111-->
112
113* {string}
114
115Provides the platform-specific path delimiter:
116
117* `;` for Windows
118* `:` for POSIX
119
120For example, on POSIX:
121
122```js
123console.log(process.env.PATH);
124// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
125
126process.env.PATH.split(path.delimiter);
127// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
128```
129
130On Windows:
131
132```js
133console.log(process.env.PATH);
134// Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'
135
136process.env.PATH.split(path.delimiter);
137// Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
138```
139
140## `path.dirname(path)`
141
142<!-- YAML
143added: v0.1.16
144changes:
145  - version: v6.0.0
146    pr-url: https://github.com/nodejs/node/pull/5348
147    description: Passing a non-string as the `path` argument will throw now.
148-->
149
150* `path` {string}
151* Returns: {string}
152
153The `path.dirname()` method returns the directory name of a `path`, similar to
154the Unix `dirname` command. Trailing directory separators are ignored, see
155[`path.sep`][].
156
157```js
158path.dirname('/foo/bar/baz/asdf/quux');
159// Returns: '/foo/bar/baz/asdf'
160```
161
162A [`TypeError`][] is thrown if `path` is not a string.
163
164## `path.extname(path)`
165
166<!-- YAML
167added: v0.1.25
168changes:
169  - version: v6.0.0
170    pr-url: https://github.com/nodejs/node/pull/5348
171    description: Passing a non-string as the `path` argument will throw now.
172-->
173
174* `path` {string}
175* Returns: {string}
176
177The `path.extname()` method returns the extension of the `path`, from the last
178occurrence of the `.` (period) character to end of string in the last portion of
179the `path`. If there is no `.` in the last portion of the `path`, or if
180there are no `.` characters other than the first character of
181the basename of `path` (see `path.basename()`) , an empty string is returned.
182
183```js
184path.extname('index.html');
185// Returns: '.html'
186
187path.extname('index.coffee.md');
188// Returns: '.md'
189
190path.extname('index.');
191// Returns: '.'
192
193path.extname('index');
194// Returns: ''
195
196path.extname('.index');
197// Returns: ''
198
199path.extname('.index.md');
200// Returns: '.md'
201```
202
203A [`TypeError`][] is thrown if `path` is not a string.
204
205## `path.format(pathObject)`
206
207<!-- YAML
208added: v0.11.15
209-->
210
211* `pathObject` {Object} Any JavaScript object having the following properties:
212  * `dir` {string}
213  * `root` {string}
214  * `base` {string}
215  * `name` {string}
216  * `ext` {string}
217* Returns: {string}
218
219The `path.format()` method returns a path string from an object. This is the
220opposite of [`path.parse()`][].
221
222When providing properties to the `pathObject` remember that there are
223combinations where one property has priority over another:
224
225* `pathObject.root` is ignored if `pathObject.dir` is provided
226* `pathObject.ext` and `pathObject.name` are ignored if `pathObject.base` exists
227
228For example, on POSIX:
229
230```js
231// If `dir`, `root` and `base` are provided,
232// `${dir}${path.sep}${base}`
233// will be returned. `root` is ignored.
234path.format({
235  root: '/ignored',
236  dir: '/home/user/dir',
237  base: 'file.txt',
238});
239// Returns: '/home/user/dir/file.txt'
240
241// `root` will be used if `dir` is not specified.
242// If only `root` is provided or `dir` is equal to `root` then the
243// platform separator will not be included. `ext` will be ignored.
244path.format({
245  root: '/',
246  base: 'file.txt',
247  ext: 'ignored',
248});
249// Returns: '/file.txt'
250
251// `name` + `ext` will be used if `base` is not specified.
252path.format({
253  root: '/',
254  name: 'file',
255  ext: '.txt',
256});
257// Returns: '/file.txt'
258```
259
260On Windows:
261
262```js
263path.format({
264  dir: 'C:\\path\\dir',
265  base: 'file.txt',
266});
267// Returns: 'C:\\path\\dir\\file.txt'
268```
269
270## `path.isAbsolute(path)`
271
272<!-- YAML
273added: v0.11.2
274-->
275
276* `path` {string}
277* Returns: {boolean}
278
279The `path.isAbsolute()` method determines if `path` is an absolute path.
280
281If the given `path` is a zero-length string, `false` will be returned.
282
283For example, on POSIX:
284
285```js
286path.isAbsolute('/foo/bar'); // true
287path.isAbsolute('/baz/..');  // true
288path.isAbsolute('qux/');     // false
289path.isAbsolute('.');        // false
290```
291
292On Windows:
293
294```js
295path.isAbsolute('//server');    // true
296path.isAbsolute('\\\\server');  // true
297path.isAbsolute('C:/foo/..');   // true
298path.isAbsolute('C:\\foo\\..'); // true
299path.isAbsolute('bar\\baz');    // false
300path.isAbsolute('bar/baz');     // false
301path.isAbsolute('.');           // false
302```
303
304A [`TypeError`][] is thrown if `path` is not a string.
305
306## `path.join([...paths])`
307
308<!-- YAML
309added: v0.1.16
310-->
311
312* `...paths` {string} A sequence of path segments
313* Returns: {string}
314
315The `path.join()` method joins all given `path` segments together using the
316platform-specific separator as a delimiter, then normalizes the resulting path.
317
318Zero-length `path` segments are ignored. If the joined path string is a
319zero-length string then `'.'` will be returned, representing the current
320working directory.
321
322```js
323path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
324// Returns: '/foo/bar/baz/asdf'
325
326path.join('foo', {}, 'bar');
327// Throws 'TypeError: Path must be a string. Received {}'
328```
329
330A [`TypeError`][] is thrown if any of the path segments is not a string.
331
332## `path.normalize(path)`
333
334<!-- YAML
335added: v0.1.23
336-->
337
338* `path` {string}
339* Returns: {string}
340
341The `path.normalize()` method normalizes the given `path`, resolving `'..'` and
342`'.'` segments.
343
344When multiple, sequential path segment separation characters are found (e.g.
345`/` on POSIX and either `\` or `/` on Windows), they are replaced by a single
346instance of the platform-specific path segment separator (`/` on POSIX and
347`\` on Windows). Trailing separators are preserved.
348
349If the `path` is a zero-length string, `'.'` is returned, representing the
350current working directory.
351
352For example, on POSIX:
353
354```js
355path.normalize('/foo/bar//baz/asdf/quux/..');
356// Returns: '/foo/bar/baz/asdf'
357```
358
359On Windows:
360
361```js
362path.normalize('C:\\temp\\\\foo\\bar\\..\\');
363// Returns: 'C:\\temp\\foo\\'
364```
365
366Since Windows recognizes multiple path separators, both separators will be
367replaced by instances of the Windows preferred separator (`\`):
368
369```js
370path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar');
371// Returns: 'C:\\temp\\foo\\bar'
372```
373
374A [`TypeError`][] is thrown if `path` is not a string.
375
376## `path.parse(path)`
377
378<!-- YAML
379added: v0.11.15
380-->
381
382* `path` {string}
383* Returns: {Object}
384
385The `path.parse()` method returns an object whose properties represent
386significant elements of the `path`. Trailing directory separators are ignored,
387see [`path.sep`][].
388
389The returned object will have the following properties:
390
391* `dir` {string}
392* `root` {string}
393* `base` {string}
394* `name` {string}
395* `ext` {string}
396
397For example, on POSIX:
398
399```js
400path.parse('/home/user/dir/file.txt');
401// Returns:
402// { root: '/',
403//   dir: '/home/user/dir',
404//   base: 'file.txt',
405//   ext: '.txt',
406//   name: 'file' }
407```
408
409```text
410┌─────────────────────┬────────────┐
411│          dir        │    base    │
412├──────┬              ├──────┬─────┤
413│ root │              │ name │ ext │
414"  /    home/user/dir / file  .txt "
415└──────┴──────────────┴──────┴─────┘
416(All spaces in the "" line should be ignored. They are purely for formatting.)
417```
418
419On Windows:
420
421```js
422path.parse('C:\\path\\dir\\file.txt');
423// Returns:
424// { root: 'C:\\',
425//   dir: 'C:\\path\\dir',
426//   base: 'file.txt',
427//   ext: '.txt',
428//   name: 'file' }
429```
430
431```text
432┌─────────────────────┬────────────┐
433│          dir        │    base    │
434├──────┬              ├──────┬─────┤
435│ root │              │ name │ ext │
436" C:\      path\dir   \ file  .txt "
437└──────┴──────────────┴──────┴─────┘
438(All spaces in the "" line should be ignored. They are purely for formatting.)
439```
440
441A [`TypeError`][] is thrown if `path` is not a string.
442
443## `path.posix`
444
445<!-- YAML
446added: v0.11.15
447changes:
448  - version: v15.3.0
449    pr-url: https://github.com/nodejs/node/pull/34962
450    description: Exposed as `require('path/posix')`.
451-->
452
453* {Object}
454
455The `path.posix` property provides access to POSIX specific implementations
456of the `path` methods.
457
458The API is accessible via `require('node:path').posix` or `require('node:path/posix')`.
459
460## `path.relative(from, to)`
461
462<!-- YAML
463added: v0.5.0
464changes:
465  - version: v6.8.0
466    pr-url: https://github.com/nodejs/node/pull/8523
467    description: On Windows, the leading slashes for UNC paths are now included
468                 in the return value.
469-->
470
471* `from` {string}
472* `to` {string}
473* Returns: {string}
474
475The `path.relative()` method returns the relative path from `from` to `to` based
476on the current working directory. If `from` and `to` each resolve to the same
477path (after calling `path.resolve()` on each), a zero-length string is returned.
478
479If a zero-length string is passed as `from` or `to`, the current working
480directory will be used instead of the zero-length strings.
481
482For example, on POSIX:
483
484```js
485path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
486// Returns: '../../impl/bbb'
487```
488
489On Windows:
490
491```js
492path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb');
493// Returns: '..\\..\\impl\\bbb'
494```
495
496A [`TypeError`][] is thrown if either `from` or `to` is not a string.
497
498## `path.resolve([...paths])`
499
500<!-- YAML
501added: v0.3.4
502-->
503
504* `...paths` {string} A sequence of paths or path segments
505* Returns: {string}
506
507The `path.resolve()` method resolves a sequence of paths or path segments into
508an absolute path.
509
510The given sequence of paths is processed from right to left, with each
511subsequent `path` prepended until an absolute path is constructed.
512For instance, given the sequence of path segments: `/foo`, `/bar`, `baz`,
513calling `path.resolve('/foo', '/bar', 'baz')` would return `/bar/baz`
514because `'baz'` is not an absolute path but `'/bar' + '/' + 'baz'` is.
515
516If, after processing all given `path` segments, an absolute path has not yet
517been generated, the current working directory is used.
518
519The resulting path is normalized and trailing slashes are removed unless the
520path is resolved to the root directory.
521
522Zero-length `path` segments are ignored.
523
524If no `path` segments are passed, `path.resolve()` will return the absolute path
525of the current working directory.
526
527```js
528path.resolve('/foo/bar', './baz');
529// Returns: '/foo/bar/baz'
530
531path.resolve('/foo/bar', '/tmp/file/');
532// Returns: '/tmp/file'
533
534path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
535// If the current working directory is /home/myself/node,
536// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'
537```
538
539A [`TypeError`][] is thrown if any of the arguments is not a string.
540
541## `path.sep`
542
543<!-- YAML
544added: v0.7.9
545-->
546
547* {string}
548
549Provides the platform-specific path segment separator:
550
551* `\` on Windows
552* `/` on POSIX
553
554For example, on POSIX:
555
556```js
557'foo/bar/baz'.split(path.sep);
558// Returns: ['foo', 'bar', 'baz']
559```
560
561On Windows:
562
563```js
564'foo\\bar\\baz'.split(path.sep);
565// Returns: ['foo', 'bar', 'baz']
566```
567
568On Windows, both the forward slash (`/`) and backward slash (`\`) are accepted
569as path segment separators; however, the `path` methods only add backward
570slashes (`\`).
571
572## `path.toNamespacedPath(path)`
573
574<!-- YAML
575added: v9.0.0
576-->
577
578* `path` {string}
579* Returns: {string}
580
581On Windows systems only, returns an equivalent [namespace-prefixed path][] for
582the given `path`. If `path` is not a string, `path` will be returned without
583modifications.
584
585This method is meaningful only on Windows systems. On POSIX systems, the
586method is non-operational and always returns `path` without modifications.
587
588## `path.win32`
589
590<!-- YAML
591added: v0.11.15
592changes:
593  - version: v15.3.0
594    pr-url: https://github.com/nodejs/node/pull/34962
595    description: Exposed as `require('path/win32')`.
596-->
597
598* {Object}
599
600The `path.win32` property provides access to Windows-specific implementations
601of the `path` methods.
602
603The API is accessible via `require('node:path').win32` or `require('node:path/win32')`.
604
605[MSDN-Rel-Path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths
606[`TypeError`]: errors.md#class-typeerror
607[`path.parse()`]: #pathparsepath
608[`path.posix`]: #pathposix
609[`path.sep`]: #pathsep
610[`path.win32`]: #pathwin32
611[namespace-prefixed path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#namespaces
612