Node.js中路径处理模块path详解

2020-06-17 07:06:40易采站长站整理

把paths拼起来,然后再normalize一下。这句话反正我自己看着也是莫名其妙,可以参考下面的伪代码定义。

例子如下:


var path = require('path');

// 输出 '/foo/bar/baz/asdf'
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');

path定义的伪代码如下:


module.exports.join = function(){
var paths = Array.prototye.slice.call(arguments, 0);
return this.normalize( paths.join('/') );
};

path.resolve([…paths])

这个接口的说明有点啰嗦。你可以想象现在你在shell下面,从左到右运行一遍cd path命令,最终获取的绝对路径/文件名,就是这个接口所返回的结果了。

比如

path.resolve('/foo/bar', './baz')
可以看成下面命令的结果


cd /foo/bar
cd ./baz

更多对比例子如下:


var path = require('path');

// 假设当前工作路径是 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path

// 输出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path
console.log( path.resolve('') )

// 输出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path
console.log( path.resolve('.') )

// 输出 /foo/bar/baz
console.log( path.resolve('/foo/bar', './baz') );

// 输出 /foo/bar/baz
console.log( path.resolve('/foo/bar', './baz/') );

// 输出 /tmp/file
console.log( path.resolve('/foo/bar', '/tmp/file/') );

// 输出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path/www/js/mod.js
console.log( path.resolve('www', 'js/upload', '../mod.js') );

路径解析

path.parse(path)

path.normalize(filepath)

从官方文档的描述来看,

path.normalize(filepath) 
应该是比较简单的一个API,不过用起来总是觉得没底。

为什么呢?API说明过于简略了,包括如下:

      如果路径为空,返回.,相当于当前的工作路径。

      将对路径中重复的路径分隔符(比如linux下的/)合并为一个。

      对路径中的.、..进行处理。(类似于shell里的cd ..)

      如果路径最后有/,那么保留该/。

感觉stackoverflow上一个兄弟对这个API的解释更实在,原文链接。


In other words, path.normalize is "What is the shortest path I can take that will take me to the same place as the input"