首页 > 解决方案 > Node.js:检查 path.format() 的根

问题描述

请参阅以下示例path.format()

require('path').format({ root: '/Users/joe', name: 'test', ext: 'txt' }) //  '/Users/joe/test.txt'

这个例子写在nodejs.dev中,据说输出如下:

/Users/joe/test.txt

但是我在Linux和Windows上都测试过这段代码,结果如下:

/Users/joetesttxt

造成这种差异的原因是什么?
这个网站的例子错了吗?

标签: node.jspath

解决方案


所示示例适用于 POSIX,其中 Windows 和 Linux 有不同的执行方式(因为文件结构的差异)。

如果我们使用相反的函数parse,并转换C:\\Users\\joe\\test.txt为我们需要使用的对象format,我们得到。

path.parse('C:\\Users\\joe\\test.txt')
// returns
{
  root: 'C:\\',
  dir: 'C:\\Users\\joe',
  base: 'test.txt',
  ext: '.txt',
  name: 'test'
}

因此,这提供了一个示例,说明您需要format为 Windows 提供什么。

如果我们在 Linux 中做同样的事情,我们会得到。

path.parse('/home/joe/test.txt')
{
  root: '/',
  dir: '/home/joe',
  base: 'test.txt',
  ext: '.txt',
  name: 'test'
}

然而,我们可以省略root和,base因为它们分别在dir和中表示name+ext


推荐阅读