Node.js:检查路径的根.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

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

显示的示例是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'
}

我们可以省略rootbase,因为它们分别在dirname+ext中表示。

最新更新