|
|
|
@ -252,6 +252,24 @@ path.extname('/home/jane/file.txt')
@@ -252,6 +252,24 @@ path.extname('/home/jane/file.txt')
|
|
|
|
|
|
|
|
|
|
## `path.format()` 从路径对象中创建路径 |
|
|
|
|
|
|
|
|
|
和 `path.parse()` 的作用相反,`path.format` 用于从路径对象中生成对应的路径并返回 |
|
|
|
|
和 `path.parse()` 的作用相反,`path.format()` 用于从路径对象中生成对应的路径并返回 |
|
|
|
|
|
|
|
|
|
例子:改变文件拓展名 |
|
|
|
|
例子:改变文件拓展名 |
|
|
|
|
|
|
|
|
|
```javascript |
|
|
|
|
const changeFilenameExtension = (pathStr, newExtension) => { |
|
|
|
|
if (!newExtension.startsWith(".")) { |
|
|
|
|
throw new Error( |
|
|
|
|
"Extension must start with a dot: " + |
|
|
|
|
JSON.stringify(newExtension) |
|
|
|
|
); |
|
|
|
|
} |
|
|
|
|
const parts = path.parse(pathStr); |
|
|
|
|
return path.format({ |
|
|
|
|
...parts, |
|
|
|
|
// prevent .base from overriding .name and .ext |
|
|
|
|
base: undefined, |
|
|
|
|
ext: newExtension, |
|
|
|
|
}); |
|
|
|
|
}; |
|
|
|
|
``` |