Nodejs: path summary of the path Processing Module

Source: Internet
Author: User
In node. JS, path is a frequently used but hateful module. This is partly because the document is not clear enough, and partly because of platform differences of interfaces. Module Overview

In node. JS, path is a frequently used but hateful module. This is partly because the document is not clear enough, and partly because of platform differences of interfaces.

Classify the path interface according to its purpose, so it is not that difficult to understand.

Get path/file name/Extension

Obtain path: path. dirname (filepath)

Get File Name: path. basename (filepath)

Obtain the extension path. extname (filepath)

Obtain the path

Example:

Var path = require ('path'); var filepath = '/tmp/demo/js/test. js'; // output:/tmp/demo/js console. log (path. dirname (filepath ));

Get File Name

Strictly speaking, path. basename (filepath) is only the last part of the output path and does not determine whether the file name is used.

But most of the time, we can use it as a simple "Get File Name" method.

Var path = require ('path'); // output: test. js console. log (path. basename ('/tmp/demo/js/test. js '); // output: test console. log (path. basename ('/tmp/demo/js/test/'); // output: test console. log (path. basename ('/tmp/demo/js/test '));

What if I only want to get the file name, but does not include the file extension? The second parameter can be used.

// Output: test console. log (path. basename ('/tmp/demo/js/test. js','. js '));

Get File Extension

A simple example is as follows:

Var path = require ('path'); var filepath = '/tmp/demo/js/test. js'; // output :. js console. log (path. extname (filepath ));

The more detailed rules are as follows: (assume path. basename (filepath) = B)

It starts from the last. of B and ends with the last character.

If B does not exist. Or the first character of B is., an empty string is returned.

See examples in the official documentation

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])

Combine paths and then normalize it. This sentence is inexplicable to me. You can refer to the following definition of pseudo code.

Example:

Var path = require ('path'); // output '/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 cool. As you can imagine, you can run the cd path command from left to right under the shell to obtain the absolute path/file name, which is the result returned by this interface.

For example, path. resolve ('/foo/bar','./Baz') can be viewed as the result of the following command:

cd /foo/bar cd ./baz

More examples are as follows:

Var path = require ('path '); // assume that the current working path is/Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path // output/Users/a/Documents /git-code/nodejs-learning-guide/examples/2016.11.08-node-path console. log (path. resolve ('') // output/Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path console. log (path. resolve ('. ') // output/foo/bar/baz console. log (path. resolve ('/foo/bar ','. /Baz'); // output/foo/bar/baz console. log (path. resolve ('/foo/bar ','. /baz/'); // output/tmp/file console. log (path. resolve ('/foo/bar','/tmp/file /')); // output/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 Parsing

Path. parse (path)

Path. normalize (filepath)

From the description in the official document, path. normalize (filepath) should be a relatively simple API, but it is always useless.

Why? The API description is too simple, including:

If the path is null, return., which is equivalent to the current working path.

Combine duplicate path delimiters (such as linux/) in the path into one.

Process... in the path. (Similar to the cd .. in shell ..)

If the path has a slash (/), keep the slash /.

It seems that a brother on stackoverflow explained this API more realistically.

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"

The sample code is as follows. We recommend that you copy the code and run it to see the actual results.

Var path = require ('path'); var filepath = '/tmp/demo/js/test. js'; var index = 0; var compare = function (desc, callback) {console. log ('[Use Case % d]: % s', ++ index, desc); callback (); console. log ('\ n') ;}; compare ('path is null', function () {// output. console. log (path. normalize ('');}); compare ('specifies whether the path ends with/', function () {// output/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 ('repeated/', function () {// output/tmp/demo/js console. log (path. normalize ('/tmp/demo // js');}); compare (' path .. ', function () {// output/tmp/demo/js console. log (path. normalize ('/tmp/demo/js/upload /.. ');}); compare ('relative path', function () {// output demo/js/upload/console. log (path. normalize ('. /demo/js/upload/'); // outputs demo/js/upload/console. log (path. normalize ('demo/js/upload/');}); compare ('noncommonly used boundary', function () {// output .. console. log (path. normalize ('. /.. '); // output .. console. log (path. normalize ('.. '); // output .. /console. log (path. normalize ('.. /'); // output/console. log (path. normalize ('/.. /'); // output/console. log (path. normalize ('/.. '));});

If you are interested, you can refer to the node source code of path. normalize (filepath) as follows:

File Path decomposition/Combination

Path. format (pathObject): combines the root, dir, base, name, and ext attributes of pathObject into a file path according to certain rules.

Path. parse (filepath): reverse operation of path. format.

Let's take a look at the official website's description of relevant attributes.

First, in linux

┌─────────────────────┬────────────┐ │          dir        │    base    │ ├──────┬              ├──────┬─────┤ │ root │              │ name │ ext │ "  /    home/user/dir / file  .txt " └──────┴──────────────┴──────┴─────┘ (all spaces in the "" line should be ignored -- they are purely for formatting)

In 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)

After reading the relevant API documentation, we found that the Configuration Attribute of pathObject can be further simplified in path. format (pathObject.

According to the interface description, the following two are equivalent.

Root vs dir: the two can be replaced with each other. The difference is that, when the path is spliced,/is not automatically added after root, and dir will.

Base vs name + ext: the two can be replaced with each other.

Var path = require ('path'); var p1 = path. format ({root: '/tmp/', base: 'Hello. js '}); console. log (p1); // output/tmp/hello. js var p2 = path. format ({dir: '/tmp', name: 'hello', ext :'. js '}); console. log (p2); // output/tmp/hello. js

Path. parse (filepath)

Path. format (pathObject) reverse operation, directly on the official website example.

Four attributes are convenient for users, but path. format (pathObject) is also four configuration attributes, which is easy to confuse.

path.parse('/home/user/dir/file.txt') // returns // { //    root : "/", //    dir : "/home/user/dir", //    base : "file.txt", //    ext : ".txt", //    name : "file" // }

Obtain relative path

Interface: path. relative (from,)

Description: The relative path from the from path to the to path.

Boundary:

If from and to point to the same path, an empty string is returned.

If any of the from and to fields is empty, the current working path is returned.

Example above:

Var path = require ('path'); var p1 = path. relative ('/data/orandea/test/aaa','/data/orandea/impl/bbb'); console. log (p1); // output ".. /.. /impl/bbb "var p2 = path. relative ('/data/demo','/data/demo'); console. log (p2); // output "" var p3 = path. relative ('/data/demo', ''); console. log (p3); // output ".. /.. /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path"

Platform related interfaces/attributes

The following attributes and interfaces are related to the specific implementation of the Platform. That is to say, the same attributes and interfaces have different performance on different platforms.

Path. posix: linux implementation of path related attributes and interfaces.

Path. win32: win32 Implementation of path-related attributes and interfaces.

Path. sep: path separator. On linux, It is/and on windows, it is ''.

Path. delimiter: delimiter set by path. On linux: On windows, yes ;.

Note: When the path. win32 interface is used, the parameter can also use/as the separator, but the delimiter returned by the interface will only be ''.

The example is more intuitive.

> 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 system example:

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 example:

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\\']

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.