PageRenderTime 280ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/doc/api/path.md

https://gitlab.com/CORP-RESELLER/node
Markdown | 515 lines | 382 code | 133 blank | 0 comment | 0 complexity | 302d2ccc3f9ef11312f98a062fd84c6b MD5 | raw file
  1. # Path
  2. > Stability: 2 - Stable
  3. The `path` module provides utilities for working with file and directory paths.
  4. It can be accessed using:
  5. ```js
  6. const path = require('path');
  7. ```
  8. ## Windows vs. POSIX
  9. The default operation of the `path` module varies based on the operating system
  10. on which a Node.js application is running. Specifically, when running on a
  11. Windows operating system, the `path` module will assume that Windows-style
  12. paths are being used.
  13. For example, using the `path.basename()` function with the Windows file path
  14. `C:\temp\myfile.html`, will yield different results when running on POSIX than
  15. when run on Windows:
  16. On POSIX:
  17. ```js
  18. path.basename('C:\\temp\\myfile.html');
  19. // returns 'C:\temp\myfile.html'
  20. ```
  21. On Windows:
  22. ```js
  23. path.basename('C:\\temp\\myfile.html');
  24. // returns 'myfile.html'
  25. ```
  26. To achieve consistent results when working with Windows file paths on any
  27. operating system, use [`path.win32`][]:
  28. On POSIX and Windows:
  29. ```js
  30. path.win32.basename('C:\\temp\\myfile.html');
  31. // returns 'myfile.html'
  32. ```
  33. To achieve consistent results when working with POSIX file paths on any
  34. operating system, use [`path.posix`][]:
  35. On POSIX and Windows:
  36. ```js
  37. path.posix.basename('/tmp/myfile.html');
  38. // returns 'myfile.html'
  39. ```
  40. ## path.basename(path[, ext])
  41. <!-- YAML
  42. added: v0.1.25
  43. -->
  44. * `path` {String}
  45. * `ext` {String} An optional file extension
  46. The `path.basename()` methods returns the last portion of a `path`, similar to
  47. the Unix `basename` command.
  48. For example:
  49. ```js
  50. path.basename('/foo/bar/baz/asdf/quux.html')
  51. // returns 'quux.html'
  52. path.basename('/foo/bar/baz/asdf/quux.html', '.html')
  53. // returns 'quux'
  54. ```
  55. A [`TypeError`][] is thrown if `path` is not a string or if `ext` is given
  56. and is not a string.
  57. ## path.delimiter
  58. <!-- YAML
  59. added: v0.9.3
  60. -->
  61. Provides the platform-specific path delimiter:
  62. * `;` for Windows
  63. * `:` for POSIX
  64. For example, on POSIX:
  65. ```js
  66. console.log(process.env.PATH)
  67. // '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
  68. process.env.PATH.split(path.delimiter)
  69. // returns ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
  70. ```
  71. On Windows:
  72. ```js
  73. console.log(process.env.PATH)
  74. // 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'
  75. process.env.PATH.split(path.delimiter)
  76. // returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
  77. ```
  78. ## path.dirname(path)
  79. <!-- YAML
  80. added: v0.1.16
  81. -->
  82. * `path` {String}
  83. The `path.dirname()` method returns the directory name of a `path`, similar to
  84. the Unix `dirname` command.
  85. For example:
  86. ```js
  87. path.dirname('/foo/bar/baz/asdf/quux')
  88. // returns '/foo/bar/baz/asdf'
  89. ```
  90. A [`TypeError`][] is thrown if `path` is not a string.
  91. ## path.extname(path)
  92. <!-- YAML
  93. added: v0.1.25
  94. -->
  95. * `path` {String}
  96. The `path.extname()` method returns the extension of the `path`, from the last
  97. occurance of the `.` (period) character to end of string in the last portion of
  98. the `path`. If there is no `.` in the last portion of the `path`, or if the
  99. first character of the basename of `path` (see `path.basename()`) is `.`, then
  100. an empty string is returned.
  101. For example:
  102. ```js
  103. path.extname('index.html')
  104. // returns '.html'
  105. path.extname('index.coffee.md')
  106. // returns '.md'
  107. path.extname('index.')
  108. // returns '.'
  109. path.extname('index')
  110. // returns ''
  111. path.extname('.index')
  112. // returns ''
  113. ```
  114. A [`TypeError`][] is thrown if `path` is not a string.
  115. ## path.format(pathObject)
  116. <!-- YAML
  117. added: v0.11.15
  118. -->
  119. * `pathObject` {Object}
  120. * `dir` {String}
  121. * `root` {String}
  122. * `base` {String}
  123. * `name` {String}
  124. * `ext` {String}
  125. The `path.format()` method returns a path string from an object. This is the
  126. opposite of [`path.parse()`][].
  127. The following process is used when constructing the path string:
  128. * `output` is set to an empty string.
  129. * If `pathObject.dir` is specified, `pathObject.dir` is appended to `output`
  130. followed by the value of `path.sep`;
  131. * Otherwise, if `pathObject.root` is specified, `pathObject.root` is appended
  132. to `output`.
  133. * If `pathObject.base` is specified, `pathObject.base` is appended to `output`;
  134. * Otherwise:
  135. * If `pathObject.name` is specified, `pathObject.name` is appended to `output`
  136. * If `pathObject.ext` is specified, `pathObject.ext` is appended to `output`.
  137. * Return `output`
  138. For example, on POSIX:
  139. ```js
  140. // If `dir` and `base` are provided,
  141. // `${dir}${path.sep}${base}`
  142. // will be returned.
  143. path.format({
  144. dir: '/home/user/dir',
  145. base: 'file.txt'
  146. });
  147. // returns '/home/user/dir/file.txt'
  148. // `root` will be used if `dir` is not specified.
  149. // If only `root` is provided or `dir` is equal to `root` then the
  150. // platform separator will not be included.
  151. path.format({
  152. root: '/',
  153. base: 'file.txt'
  154. });
  155. // returns '/file.txt'
  156. // `name` + `ext` will be used if `base` is not specified.
  157. path.format({
  158. root: '/',
  159. name: 'file',
  160. ext: '.txt'
  161. });
  162. // returns '/file.txt'
  163. // `base` will be returned if `dir` or `root` are not provided.
  164. path.format({
  165. base: 'file.txt'
  166. });
  167. // returns 'file.txt'
  168. ```
  169. On Windows:
  170. ```js
  171. path.format({
  172. root : "C:\\",
  173. dir : "C:\\path\\dir",
  174. base : "file.txt",
  175. ext : ".txt",
  176. name : "file"
  177. });
  178. // returns 'C:\\path\\dir\\file.txt'
  179. ```
  180. ## path.isAbsolute(path)
  181. <!-- YAML
  182. added: v0.11.2
  183. -->
  184. * `path` {String}
  185. The `path.isAbsolute()` method determines if `path` is an absolute path.
  186. If the given `path` is a zero-length string, `false` will be returned.
  187. For example on POSIX:
  188. ```js
  189. path.isAbsolute('/foo/bar') // true
  190. path.isAbsolute('/baz/..') // true
  191. path.isAbsolute('qux/') // false
  192. path.isAbsolute('.') // false
  193. ```
  194. On Windows:
  195. ```js
  196. path.isAbsolute('//server') // true
  197. path.isAbsolute('C:/foo/..') // true
  198. path.isAbsolute('bar\\baz') // false
  199. path.isAbsolute('.') // false
  200. ```
  201. A [`TypeError`][] is thrown if `path` is not a string.
  202. ## path.join([path[, ...]])
  203. <!-- YAML
  204. added: v0.1.16
  205. -->
  206. * `[path[, ...]]` {String} A sequence of path segments
  207. The `path.join()` method join all given `path` segments together using the
  208. platform specific separator as a delimiter, then normalizes the resulting path.
  209. Zero-length `path` segments are ignored. If the joined path string is a
  210. zero-length string then `'.'` will be returned, representing the current
  211. working directory.
  212. For example:
  213. ```js
  214. path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
  215. // returns '/foo/bar/baz/asdf'
  216. path.join('foo', {}, 'bar')
  217. // throws TypeError: Arguments to path.join must be strings
  218. ```
  219. A [`TypeError`][] is thrown if any of the path segments is not a string.
  220. ## path.normalize(path)
  221. <!-- YAML
  222. added: v0.1.23
  223. -->
  224. * `path` {String}
  225. The `path.normalize()` method normalizes the given `path`, resolving `'..'` and
  226. `'.'` segments.
  227. When multiple, sequential path segment separation characters are found (e.g.
  228. `/` on POSIX and `\` on Windows), they are replaced by a single instance of the
  229. platform specific path segment separator. Trailing separators are preserved.
  230. If the `path` is a zero-length string, `'.'` is returned, representing the
  231. current working directory.
  232. For example on POSIX:
  233. ```js
  234. path.normalize('/foo/bar//baz/asdf/quux/..')
  235. // returns '/foo/bar/baz/asdf'
  236. ```
  237. On Windows:
  238. ```js
  239. path.normalize('C:\\temp\\\\foo\\bar\\..\\');
  240. // returns 'C:\\temp\\foo\\'
  241. ```
  242. A [`TypeError`][] is thrown if `path` is not a string.
  243. ## path.parse(path)
  244. <!-- YAML
  245. added: v0.11.15
  246. -->
  247. * `path` {String}
  248. The `path.parse()` method returns an object whose properties represent
  249. significant elements of the `path`.
  250. The returned object will have the following properties:
  251. * `root` {String}
  252. * `dir` {String}
  253. * `base` {String}
  254. * `ext` {String}
  255. * `name` {String}
  256. For example on POSIX:
  257. ```js
  258. path.parse('/home/user/dir/file.txt')
  259. // returns
  260. // {
  261. // root : "/",
  262. // dir : "/home/user/dir",
  263. // base : "file.txt",
  264. // ext : ".txt",
  265. // name : "file"
  266. // }
  267. ```
  268. ```text
  269. ┌─────────────────────┬────────────┐
  270. │ dir │ base │
  271. ├──────┬ ├──────┬─────┤
  272. │ root │ │ name │ ext │
  273. " / home/user/dir / file .txt "
  274. └──────┴──────────────┴──────┴─────┘
  275. (all spaces in the "" line should be ignored -- they are purely for formatting)
  276. ```
  277. On Windows:
  278. ```js
  279. path.parse('C:\\path\\dir\\file.txt')
  280. // returns
  281. // {
  282. // root : "C:\\",
  283. // dir : "C:\\path\\dir",
  284. // base : "file.txt",
  285. // ext : ".txt",
  286. // name : "file"
  287. // }
  288. ```
  289. ```text
  290. ┌─────────────────────┬────────────┐
  291. │ dir │ base │
  292. ├──────┬ ├──────┬─────┤
  293. │ root │ │ name │ ext │
  294. " C:\ path\dir \ file .txt "
  295. └──────┴──────────────┴──────┴─────┘
  296. (all spaces in the "" line should be ignored -- they are purely for formatting)
  297. ```
  298. A [`TypeError`][] is thrown if `path` is not a string.
  299. ## path.posix
  300. <!-- YAML
  301. added: v0.11.15
  302. -->
  303. The `path.posix` property provides access to POSIX specific implementations
  304. of the `path` methods.
  305. ## path.relative(from, to)
  306. <!-- YAML
  307. added: v0.5.0
  308. -->
  309. * `from` {String}
  310. * `to` {String}
  311. The `path.relative()` method returns the relative path from `from` to `to`.
  312. If `from` and `to` each resolve to the same path (after calling `path.resolve()`
  313. on each), a zero-length string is returned.
  314. If a zero-length string is passed as `from` or `to`, the current working
  315. directory will be used instead of the zero-length strings.
  316. For example on POSIX:
  317. ```js
  318. path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
  319. // returns '../../impl/bbb'
  320. ```
  321. On Windows:
  322. ```js
  323. path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
  324. // returns '..\\..\\impl\\bbb'
  325. ```
  326. A [`TypeError`][] is thrown if neither `from` nor `to` is a string.
  327. ## path.resolve([path[, ...]])
  328. <!-- YAML
  329. added: v0.3.4
  330. -->
  331. * `[path[, ...]]` {String} A sequence of paths or path segments
  332. The `path.resolve()` method resolves a sequence of paths or path segments into
  333. an absolute path.
  334. The given sequence of paths is processed from right to left, with each
  335. subsequent `path` prepended until an absolute path is constructed.
  336. For instance, given the sequence of path segments: `/foo`, `/bar`, `baz`,
  337. calling `path.resolve('/foo', '/bar', 'baz')` would return `/bar/baz`.
  338. If after processing all given `path` segments an absolute path has not yet
  339. been generated, the current working directory is used.
  340. The resulting path is normalized and trailing slashes are removed unless the
  341. path is resolved to the root directory.
  342. Zero-length `path` segments are ignored.
  343. If no `path` segments are passed, `path.resolve()` will return the absolute path
  344. of the current working directory.
  345. For example:
  346. ```js
  347. path.resolve('/foo/bar', './baz')
  348. // returns '/foo/bar/baz'
  349. path.resolve('/foo/bar', '/tmp/file/')
  350. // returns '/tmp/file'
  351. path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
  352. // if the current working directory is /home/myself/node,
  353. // this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'
  354. ```
  355. A [`TypeError`][] is thrown if any of the arguments is not a string.
  356. ## path.sep
  357. <!-- YAML
  358. added: v0.7.9
  359. -->
  360. Provides the platform-specific path segment separator:
  361. * `\` on Windows
  362. * `/` on POSIX
  363. For example on POSIX:
  364. ```js
  365. 'foo/bar/baz'.split(path.sep)
  366. // returns ['foo', 'bar', 'baz']
  367. ```
  368. On Windows:
  369. ```js
  370. 'foo\\bar\\baz'.split(path.sep)
  371. // returns ['foo', 'bar', 'baz']
  372. ```
  373. ## path.win32
  374. <!-- YAML
  375. added: v0.11.15
  376. -->
  377. The `path.win32` property provides access to Windows-specific implementations
  378. of the `path` methods.
  379. [`path.posix`]: #path_path_posix
  380. [`path.win32`]: #path_path_win32
  381. [`path.parse()`]: #path_path_parse_path
  382. [`TypeError`]: errors.html#errors_class_typeerror