1、=require(path);2. varfilepath/tmp/demo/js/test.js;3. 4. /输出:/tmp/demo/js5. console.log(path.dirname(filepath)获取文件名严格意义上来说,path.basename(filepath) 只是输出路径的最后一部分,并不会判断是否文件名。但大部分时候,我们可以用它来作为简易的“获取文件名“的方法。2. 3. /test.js4. console.log(path.basename()5. 6. /test7. console.log(/tmp/demo/js/test/8. 9. /10. c
2、onsole.log(/tmp/demo/js/test如果只想获取文件名,单不包括文件扩展呢?可以用上第二个参数。1. /2. console.log(,.js获取文件扩展名简单的例子如下:.jspath.extname(filepath)更详细的规则是如下:(假设 path.basename(filepath) = B ) 从B的最后一个.开始截取,直到最后一个字符。 如果B中不存在.,或者B的第一个字符就是.,那么返回空字符串。直接看官方文档的例子1. path.extname(index.html2. /returns.html4. path.extname(index.coffee.
3、md5. /.md6. 7. path.extname(index.8. /.9. 10. path.extname(index11. /12. 13. path.extname(.index14. /路径组合 path.join(.paths) path.resolve(.paths)path.join(.paths)把paths拼起来,然后再normalize一下。这句话反正我自己看着也是莫名其妙,可以参考下面的伪代码定义。输出/foo/bar/baz/asdf4. path.join(/foobarbaz/asdfquux.path定义的伪代码如下:1. module.exports.j
4、oinfunction()varpathsArray.prototye.slice.call(arguments,0);returnthis.normalize(paths.join(/4. ;path.resolve(.paths)这个接口的说明有点啰嗦。你可以想象现在你在shell下面,从左到右运行一遍cd path命令,最终获取的绝对路径/文件名,就是这个接口所返回的结果了。比如 path.resolve(/foo/bar, ./baz) 可以看成下面命令的结果1. cd/foo/bar2. cd./baz更多对比例子如下:假设当前工作路径是/Users/a/Documents/git-
5、code/nodejs-learning-guide/examples/2016.11.08-node-path4. 6. console.log(path.resolve(7. 9. console.log(10. /foo/bar/baz12. console.log(13. 15. console.log(./baz/16. 17. /tmp/file18. console.log(/tmp/file/19. 20. /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path/www/js
6、/mod.js21. console.log(wwwjs/upload./mod.js路径解析path.parse(path)path.normalize(filepath)从官方文档的描述来看,path.normalize(filepath) 应该是比较简单的一个API,不过用起来总是觉得没底。为什么呢?API说明过于简略了,包括如下: 如果路径为空,返回.,相当于当前的工作路径。 将对路径中重复的路径分隔符(比如linux下的/)合并为一个。 对路径中的.、.进行处理。(类似于shell里的cd .) 如果路径最后有/,那么保留该/。感觉stackoverflow上一个兄弟对这个API的解
7、释更实在,原文链接。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代码示例如下。建议读者把代码拷贝出来运行下,看下实际效果。4. varindex0;6. varcomparefunction(desc,callback)console.log(用例%d:%s+index,desc);callback();n10. ;11. 12. compare(路径为空/.14. console.log(path.n
8、ormalize(15. );17. compare(路径结尾是否带/18. /tmp/demo/js/upload/tmp/demo/js/upload20. 21. /tmp/demo/js/upload/22. /tmp/demo/js/upload/23. );24. 25. compare(重复的/26. 27. /tmp/demo/js28. );29. 30. compare(路径带.31. 32. /tmp/demo/js/upload/.33. );34. 35. compare(相对路径36. demo/js/upload/37. ./demo/js/upload/38. 39. 40. demo/js/upload/41. );42. 43. compare(不常用边界44. .45. ./.46. 47. 48. 49. 50. ./51. ./52. 53. /54. /./55. 56.
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1