Node.js Path Processing module path detailed _node.js

Source: Internet
Author: User
Tags win32

Objective

In Node.js, a path block is provided, in which many of the methods and attributes that are used to process and transform paths are provided, and the path interface is sorted by purpose, and it is less puzzling to ponder over it. Let's take a detailed description of PATH processing module path in Node.js.

Get path/file name/extension

Get path:path.dirname(filepath)

Get file name:path.basename(filepath)

Get extension:path.extname(filepath)

Get the path

Examples are as follows:

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, it path.basename(filepath) is just the last part of the output path and does not determine whether the file name.

But most of the time, we can use it as a simple "get filename" approach.

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 '));

If you only want to get the filename, does the file extension not include? You can use the second argument.

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

Get file name extension

The 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: (assuming path.basename(filepath) === B )

From the last one of B. Start intercepting until the last character.

If B does not exist, or the first character of B is., then returns an empty string.

An example of a direct view of the official document

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 normalize again. This sentence anyway I look at it is also baffling, you can refer to the following pseudocode definition.

Examples are as follows:

var path = require (' path ');

Output '/foo/bar/baz/asdf '
path.join ('/foo ', ' Bar ', ' baz/asdf ', ' quux ', ' ... ');

The pseudo code for path definition 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 now that you're under the shell, running the CD Path command from left to right, and finally getting the absolute path/filename, which is the result of the interface returned.

For example path.resolve('/foo/bar', './baz') , as a result of the following command

Cd/foo/bar
CD./baz

More examples of comparisons are as follows:

var path = require (' path ');

Suppose the current work 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 resolution

path.parse(path)

Path.normalize (filepath)

From the official document description, path.normalize(filepath) it should be a relatively simple API, but always feel like a bottom.

Why, then? The API description is too brief, including the following:

If the path is empty, returns., which is equivalent to the current work path.

A duplicate path delimiter (such as Linux under/) is merged into one of the paths.

to the. 、.. in the path for processing. (Similar to a CD in a shell.) )

If the path finally has/, leave the/.

Feel StackOverflow a brother the explanation of this API is more real, the original link.

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

code example below. The reader is advised to copy the code out and run it to see the actual effect.

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 empty ', function () {//output.
Console.log (Path.normalize ('));

});

 Compare (' path ends with/', function () {//Output/tmp/demo/js/upload console.log ('/tmp/demo/js/upload '));
/tmp/demo/js/upload/console.log (path.normalize ('/tmp/demo/js/upload/'));

});

Compare (' duplicate/', function () {//Output/tmp/demo/js Console.log (path.normalize ('/tmp/demo//js '));

Compare (' Path band ... ', 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/'));
Output Demo/js/upload/console.log (path.normalize (' demo/js/upload/'));

});
 Compare (' Less common boundaries ', 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 ('/.. ')); });

File path decomposition/combination

path.format(pathObject) : Will Pathobject Root, dir, base, name, ext attribute, according to certain rules, combined into a file path.

path.parse(filepath) : path.format() The reverse operation of the method.

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

First, under Linux.

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

Then, under Windows

┌─────────────────────┬────────────┐
│   dir  │base│
├──────┬    ├──────┬─────┤
│root│    │ name│ext│
"C:\  path\dir \ file. txt"
└──────┴──────────────┴──────┴─────┘
(all spaces in the "" Lin E should be ignored – they are purely for formatting)

Path.format (Pathobject)

After reading the relevant API documentation, it is found that the path.format(pathObject) configuration properties of Pathobject can be further streamlined.

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

Root vs dir: The two can replace each other, except that when the path is spliced, root is not automatically added/, and Dir will.

Base vs Name+ext: They can be replaced by 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) The reverse operation, the direct Officer network example.

The four attributes are convenient for the user, but path.format(pathObject) they are also four configuration properties that are a bit easier to confuse.

Path.parse ('/home/user/dir/file.txt ')
//returns
//{/
/root: "/",//
dir: "/home/user/dir",/
/ Base: "File.txt",
//EXT: ". txt",
//Name: "File"
///}

Get relative path

Interface:path.relative(from, to)

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.

Returns the current work path if any one in from or to is empty.

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 properties, interfaces, are related to the specific implementation of the platform. That is, the same attributes and interfaces behave differently on different platforms.

path.posix: Path-related properties, Linux implementation of the interface.

path.win32: Path-related properties, Win32 implementations of interfaces.

path.sep: Path separator. On Linux Yes/, on Windows is '.

path.delimiter: The split character for path setting. Linux is on:, Windows is;.

note that when using the Path.win32 correlation interface, the parameter can also use/make a separator, but the interface returns the value of the delimiter will only be ".

Direct examples are 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 System 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\\ ']

Summarize

The above is the entire content of this article, I hope the content of this article for everyone to learn or use Node.js can help, if there is doubt you can message exchange, thank you for the cloud Habitat Community support.

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.