国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Nodejs基礎(chǔ):路徑處理模塊path總結(jié)

Original 2016-11-14 14:02:19 661
abstract:模塊概覽在nodejs中,path是個(gè)使用頻率很高,但卻讓人又愛(ài)又恨的模塊。部分因?yàn)槲臋n說(shuō)的不夠清晰,部分因?yàn)榻涌诘钠脚_(tái)差異性。將path的接口按照用途歸類(lèi),仔細(xì)琢磨琢磨,也就沒(méi)那么費(fèi)解了。獲取路徑/文件名/擴(kuò)展名獲取路徑:path.dirname(filepath)獲取文件名:path.basename(filepath)獲取擴(kuò)展名:path.extname(filepath)獲取所在路徑例子如

模塊概覽

在nodejs中,path是個(gè)使用頻率很高,但卻讓人又愛(ài)又恨的模塊。部分因?yàn)槲臋n說(shuō)的不夠清晰,部分因?yàn)榻涌诘钠脚_(tái)差異性。

將path的接口按照用途歸類(lèi),仔細(xì)琢磨琢磨,也就沒(méi)那么費(fèi)解了。

獲取路徑/文件名/擴(kuò)展名

獲取路徑:path.dirname(filepath)

獲取文件名:path.basename(filepath)

獲取擴(kuò)展名:path.extname(filepath)

獲取所在路徑

例子如下:

var path = require('path');
var filepath = '/tmp/demo/js/test.js';

// 輸出:/tmp/demo/js
console.log( path.dirname(filepath) );

獲取文件名

嚴(yán)格意義上來(lái)說(shuō),path.basename(filepath) 只是輸出路徑的最后一部分,并不會(huì)判斷是否文件名。

但大部分時(shí)候,我們可以用它來(lái)作為簡(jiǎn)易的“獲取文件名“的方法。

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

如果只想獲取文件名,單不包括文件擴(kuò)展呢?可以用上第二個(gè)參數(shù)。

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

獲取文件擴(kuò)展名

簡(jiǎn)單的例子如下:

var path = require('path');
var filepath = '/tmp/demo/js/test.js';

// 輸出:.js
console.log( path.extname(filepath) );

更詳細(xì)的規(guī)則是如下:(假設(shè) path.basename(filepath) === B )

從B的最后一個(gè).開(kāi)始截取,直到最后一個(gè)字符。

如果B中不存在.,或者B的第一個(gè)字符就是.,那么返回空字符串。

直接看官方文檔的例子

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.join([...paths])

path.resolve([...paths])

path.join([...paths])

把paths拼起來(lái),然后再normalize一下。這句話(huà)反正我自己看著也是莫名其妙,可以參考下面的偽代碼定義。

例子如下:

var path = require('path');

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

path.join([...paths])

path.resolve([...paths])

path.join([...paths])

把paths拼起來(lái),然后再normalize一下。這句話(huà)反正我自己看著也是莫名其妙,可以參考下面的偽代碼定義。

例子如下:

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

這個(gè)接口的說(shuō)明有點(diǎn)啰嗦。你可以想象現(xiàn)在你在shell下面,從左到右運(yùn)行一遍cd path命令,最終獲取的絕對(duì)路徑/文件名,就是這個(gè)接口所返回的結(jié)果了。

比如 path.resolve('/foo/bar', './baz') 可以看成下面命令的結(jié)果

cd /foo/bar
cd ./baz

更多對(duì)比例子如下:

var path = require('path');

// 假設(shè)當(dāng)前工作路徑是 /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)

從官方文檔的描述來(lái)看,path.normalize(filepath) 應(yīng)該是比較簡(jiǎn)單的一個(gè)API,不過(guò)用起來(lái)總是覺(jué)得沒(méi)底。

為什么呢?API說(shuō)明過(guò)于簡(jiǎn)略了,包括如下:

如果路徑為空,返回.,相當(dāng)于當(dāng)前的工作路徑。

將對(duì)路徑中重復(fù)的路徑分隔符(比如linux下的/)合并為一個(gè)。

對(duì)路徑中的.、..進(jìn)行處理。(類(lèi)似于shell里的cd ..)

如果路徑最后有/,那么保留該/。

感覺(jué)stackoverflow上一個(gè)兄弟對(duì)這個(gè)API的解釋更實(shí)在,原文鏈接。

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"

代碼示例如下。建議讀者把代碼拷貝出來(lái)運(yùn)行下,看下實(shí)際效果。

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('路徑結(jié)尾是否帶/', 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('重復(fù)的/', 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('相對(duì)路徑', 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('/..') );});

感興趣的可以看下 path.normalize(filepath) 的node源碼如下:傳送門(mén)

文件路徑分解/組合

path.format(pathObject):將pathObject的root、dir、base、name、ext屬性,按照一定的規(guī)則,組合成一個(gè)文件路徑。

path.parse(filepath):path.format()方法的反向操作。

我們先來(lái)看看官網(wǎng)對(duì)相關(guān)屬性的說(shuō)明。

首先是linux下

┌─────────────────────┬────────────┐
│          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)

閱讀相關(guān)API文檔說(shuō)明后發(fā)現(xiàn),path.format(pathObject)中,pathObject的配置屬性是可以進(jìn)一步精簡(jiǎn)的。

根據(jù)接口的描述來(lái)看,以下兩者是等價(jià)的。

root vs dir:兩者可以互相替換,區(qū)別在于,路徑拼接時(shí),root后不會(huì)自動(dòng)加/,而dir會(huì)。

base vs name+ext:兩者可以互相替換。

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

path.parse(filepath)

path.format(pathObject) 的反向操作,直接上官網(wǎng)例子。

四個(gè)屬性,對(duì)于使用者是挺便利的,不過(guò)path.format(pathObject) 中也是四個(gè)配置屬性,就有點(diǎn)容易搞混。

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

獲取相對(duì)路徑

接口:path.relative(from, to)

描述:從from路徑,到to路徑的相對(duì)路徑。

邊界:

如果from、to指向同個(gè)路徑,那么,返回空字符串。

如果from、to中任一者為空,那么,返回當(dāng)前工作路徑。

上例子:

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"

平臺(tái)相關(guān)接口/屬性

以下屬性、接口,都跟平臺(tái)的具體實(shí)現(xiàn)相關(guān)。也就是說(shuō),同樣的屬性、接口,在不同平臺(tái)上的表現(xiàn)不同。

path.posix:path相關(guān)屬性、接口的linux實(shí)現(xiàn)。

path.win32:path相關(guān)屬性、接口的win32實(shí)現(xiàn)。

path.sep:路徑分隔符。在linux上是/,在windows上是\。

path.delimiter:path設(shè)置的分割符。linux上是:,windows上是;。

注意,當(dāng)使用 path.win32 相關(guān)接口時(shí),參數(shù)同樣可以使用/做分隔符,但接口返回值的分割符只會(huì)是\。

直接來(lái)例子更直觀。

> 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系統(tǒng)例子:

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系統(tǒng)例子:

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


Release Notes

Popular Entries