node.js的path模块

path模块的各种API

   path.join([...paths])

参数:paths <string> ,paths参数是字符串,这些字符串按路径片段顺序排列,(A sequence of path segments)。

返回值:Returns: <string>,也是个字符串。

join()方法将所有的路径片段以平台特定的分隔符组合在一起,然后返回标准的路径字符串。

zero-length的字符串片段会被忽略,直接返回一个'.',这个'.'代表当前的工作的路径。

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf' ----这里'..'直接返回上一层目录。

path.join('foo', {}, 'bar');
// throws 'TypeError: Path must be a string. Received {}'

path.resolve([...paths])

参数:paths <string> ,paths参数是字符串,这些字符串按路径片段或者路径顺序排列,(A sequence of path or path segments)。

返回值:Returns: <string>,也是个字符串。

path.resolve方法,将路径片段或者路径按顺序解析为绝对的路径地址。给定的路径片段按照从右到左的顺序解析,添加到最终生成的绝对路径上。

下面看几个例子:

var path = require('path');
var str = path.join('./path/./', './upload', '/file', '123.jpg');
var a = path.resolve('/foo/bar', '/tmp/file/');
var b = path.resolve('/foo/bar', './baz');
var c = path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
var d = path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile');
console.log(str);--->path/upload/file/123.jpg
console.log(a); --->/tmp/file (此处有/tmp/file的绝对地址,故直接解析成/tmp/file) 
console.log(b); ---> /foo/bar/baz ()
console.log(c); --->/Users/xuzhudong/Desktop/wwwroot/static_files/gif/image.gif(当前的工作目录是/Users/xuzhudong/Desktop/,
故解析为/Users/xuzhudong/Desktop/wwwroot/static_files/gif/image.gif)
console.log(d); --->/tmp/subfile  

path.resolve()的方法解析不是在是简单的拼接关系,而是类似 cd 命令的解析了。

 

 
原文地址:https://www.cnblogs.com/xuzhudong/p/7199769.html