This article mainly introduces the path processing module path in Node.js. It has certain reference value. Now I share it with you. Friends in need can refer to it.
I believe everyone knows that in In nodejs, path is a module that is used frequently, but that people love and hate. Because some documents are not clear enough, and some are because of platform differences in interfaces. This article will give you a detailed introduction to the path processing module path in Node.js. I hope it will be helpful to you in learning or using the module path. Let’s take a look.
Preface
In node.js, a path block is provided. In this module, many usages are provided, which can The methods and attributes used to process and convert paths are not so confusing if you classify the interfaces of paths according to their uses and think about them carefully. Below we will introduce in detail the path processing module path in Node.js.
Get path/file name/extension
Get path: path.dirname(filepath)<br>
Get the file name: path.basename(filepath)<br>
Get the extension: path.extname(filepath)<br>
Get the path
The example is as follows:
var path = require('path'); var filepath = '/tmp/demo/js/test.js'; // 输出:/tmp/demo/js console.log( path.dirname(filepath) );
Get the file name
Strictly speaking, path.basename(filepath)
is just the output path The last part does not determine whether it is a file name.
But most of the time, we can use it as a simple method of "getting the file name".
var path = require('path'); // 输出:test.js console.log( path.basename('/tmp/demo/js/test.js') ); // 输出:test console.log( path.basename('/tmp/demo/js/test/') ); // 输出:test console.log( path.basename('/tmp/demo/js/test') );
What if you only want to get the file name, but not the file extension? The second parameter can be used.
// 输出:test console.log( path.basename('/tmp/demo/js/test.js', '.js') );
Get the file extension
A simple example is as follows:
var path = require('path'); var filepath = '/tmp/demo/js/test.js'; // 输出:.js console.log( path.extname(filepath) );
The more detailed rules are as follows: (assuming path.basename(filepath) === B
)
From The last one of B. Start intercepting until the last character.
If . does not exist in B, or the first character of B is ., then an empty string is returned.
Look directly at the official documentation for examples
path.extname('index.html') // returns '.html' path.extname('index.coffee.md') // returns '.md' path.extname('index.') // returns '.' path.extname('index') // returns '' path.extname('.index') // returns ''
Path combination
path.join([...paths]) path.resolve([...paths])
path.join([...paths])
Put the paths together and then normalize them. This sentence is incomprehensible to me anyway. You can refer to the pseudocode definition below.
The example is as follows:
var path = require('path'); // 输出 '/foo/bar/baz/asdf' path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
The pseudo code defined by path is as follows:
module.exports.join = function(){ var paths = Array.prototye.slice.call(arguments, 0); return this.normalize( paths.join('/') ); };
path.resolve([...paths])
The description of this interface is a bit verbose. You can imagine that you are now running the cd path command from left to right under the shell, and the absolute path/file name finally obtained is the result returned by this interface.
For examplepath.resolve('/foo/bar', './baz')
can be seen as the result of the following command
cd /foo/bar cd ./baz
More comparison examples are as follows:
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 analysis
path.parse(path)
path.normalize(filepath)
path.normalize(filepath) should be a relatively simple API, but I always feel unsure when using it.
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"
var path = require('path'); var filepath = '/tmp/demo/js/test.js'; var index = 0; var compare = function(desc, callback){ console.log('[用例%d]:%s', ++index, desc); callback(); console.log('\n'); }; compare('路径为空', function(){ // 输出 . console.log( path.normalize('') ); }); compare('路径结尾是否带/', function(){ // 输出 /tmp/demo/js/upload console.log( path.normalize('/tmp/demo/js/upload') ); // /tmp/demo/js/upload/ console.log( path.normalize('/tmp/demo/js/upload/') ); }); compare('重复的/', function(){ // 输出 /tmp/demo/js console.log( path.normalize('/tmp/demo//js') ); }); compare('路径带..', function(){ // 输出 /tmp/demo/js console.log( path.normalize('/tmp/demo/js/upload/..') ); }); compare('相对路径', function(){ // 输出 demo/js/upload/ console.log( path.normalize('./demo/js/upload/') ); // 输出 demo/js/upload/ console.log( path.normalize('demo/js/upload/') ); }); compare('不常用边界', function(){ // 输出 .. console.log( path.normalize('./..') ); // 输出 .. console.log( path.normalize('..') ); // 输出 ../ console.log( path.normalize('../') ); // 输出 / console.log( path.normalize('/../') ); // 输出 / console.log( path.normalize('/..') ); });
File path decomposition/composition
path. format(pathObject) : Combine the root, dir, base, name, and ext attributes of pathObject into a file path according to certain rules.
path.parse(filepath) : The reverse operation of the
path.format() method.
┌─────────────────────┬────────────┐ │ dir │ base │ ├──────┬ ├──────┬─────┤ │ root │ │ name │ ext │ " / home/user/dir / file .txt " └──────┴──────────────┴──────┴─────┘ (all spaces in the "" line should be ignored -- they are purely for formatting)
然后是windows下
┌─────────────────────┬────────────┐ │ dir │ base │ ├──────┬ ├──────┬─────┤ │ root │ │ name │ ext │ " C:\ path\dir \ file .txt " └──────┴──────────────┴──────┴─────┘ (all spaces in the "" line should be ignored -- they are purely for formatting)
path.format(pathObject)
阅读相关API文档说明后发现,path.format(pathObject)
中,pathObject的配置属性是可以进一步精简的。
根据接口的描述来看,以下两者是等价的。
root vs dir:两者可以互相替换,区别在于,路径拼接时,root后不会自动加/,而dir会。
base vs name+ext:两者可以互相替换。
var path = require('path'); var p1 = path.format({ root: '/tmp/', base: 'hello.js' }); console.log( p1 ); // 输出 /tmp/hello.js var p2 = path.format({ dir: '/tmp', name: 'hello', ext: '.js' }); console.log( p2 ); // 输出 /tmp/hello.js
path.parse(filepath)
path.format(pathObject)
的反向操作,直接上官网例子。
四个属性,对于使用者是挺便利的,不过path.format(pathObject)
中也是四个配置属性,就有点容易搞混。
path.parse('/home/user/dir/file.txt') // returns // { // root : "/", // dir : "/home/user/dir", // base : "file.txt", // ext : ".txt", // name : "file" // }
获取相对路径
接口:path.relative(from, to)
描述:从from路径,到to路径的相对路径。
边界:
如果from、to指向同个路径,那么,返回空字符串。
如果from、to中任一者为空,那么,返回当前工作路径。
上例子:
var path = require('path'); var p1 = path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); console.log(p1); // 输出 "../../impl/bbb" var p2 = path.relative('/data/demo', '/data/demo'); console.log(p2); // 输出 "" var p3 = path.relative('/data/demo', ''); console.log(p3); // 输出 "../../Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path"
平台相关接口/属性
以下属性、接口,都跟平台的具体实现相关。也就是说,同样的属性、接口,在不同平台上的表现不同。
path.posix
:path相关属性、接口的linux实现。
path.win32
:path相关属性、接口的win32实现。
path.sep
:路径分隔符。在linux上是/,在windows上是``。
path.delimiter
:path设置的分割符。linux上是:,windows上是;。
注意,当使用 path.win32 相关接口时,参数同样可以使用/做分隔符,但接口返回值的分割符只会是``。
直接来例子更直观。
> path.win32.join('/tmp', 'fuck') '\\tmp\\fuck' > path.win32.sep '\\' > path.win32.join('\tmp', 'demo') '\\tmp\\demo' > path.win32.join('/tmp', 'demo') '\\tmp\\demo'
path.delimiter
linux系统例子:
console.log(process.env.PATH) // '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' process.env.PATH.split(path.delimiter) // returns ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
windows系统例子:
console.log(process.env.PATH) // 'C:\Windows\system32;C:\Windows;C:\Program Files\node\' process.env.PATH.split(path.delimiter) // returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of Introduction to path processing module path in Node.js. For more information, please follow other related articles on the PHP Chinese website!