path.format(pathObject)


path.format() 方法从一个对象返回路径字符串。这与 path.parse() 相反。

【The path.format() method returns a path string from an object. This is the opposite of path.parse().】

在为 pathObject 提供属性时,请记住某些组合中一个属性优先于另一个属性:

【When providing properties to the pathObject remember that there are combinations where one property has priority over another:】

  • 如果提供了 pathObject.dirpathObject.root 将被忽略
  • 如果存在 pathObject.base,则会忽略 pathObject.extpathObject.name

例如,在 POSIX 上:

【For example, on POSIX:】

// 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'

// `root` will be used if `dir` is not specified.
// If only `root` is provided or `dir` is equal to `root` then the
// platform separator will not be included. `ext` will be ignored.
path.format({
  root: '/',
  base: 'file.txt',
  ext: 'ignored',
});
// Returns: '/file.txt'

// `name` + `ext` will be used if `base` is not specified.
path.format({
  root: '/',
  name: 'file',
  ext: '.txt',
});
// Returns: '/file.txt'

// The dot will be added if it is not specified in `ext`.
path.format({
  root: '/',
  name: 'file',
  ext: 'txt',
});
// Returns: '/file.txt' 

在 Windows 上:

【On Windows:】

path.format({
  dir: 'C:\\path\\dir',
  base: 'file.txt',
});
// Returns: 'C:\\path\\dir\\file.txt'