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