99热99这里只有精品6国产,亚洲中文字幕在线天天更新,在线观看亚洲精品国产福利片 ,久久久久综合网

歡迎加入QQ討論群258996829
麥子學(xué)院 頭像
蘋果6袋
6
麥子學(xué)院

Nodejs基礎(chǔ):路徑處理模塊path

發(fā)布時(shí)間:2016-11-16 16:19  回復(fù):0  查看:2125   最后回復(fù):2016-11-16 16:19  

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

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

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

 ?。?nbsp;獲取路徑:path.dirname(filepath)

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

 ?。?nbsp;獲取擴(kuò)展名:path.extname(filepath)

  獲取所在路徑

  例子如下:

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

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

  獲取文件名

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

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

  var path = require('path');

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

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

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

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

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

  獲取文件擴(kuò)展名

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

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

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

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

 ?。?nbsp;B的最后一個(gè) . 開始截取,直到最后一個(gè)字符。

 ?。?nbsp;如果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 拼起來,然后再normalize一下。這句話反正我自己看著也是莫名其妙,可以參考下面的偽代碼定義。

  例子如下:

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

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

  cd /foo/barcd ./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-pathconsole.log( path.resolve('') )

  // 輸出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-pathconsole.log( path.resolve('.') )

  // 輸出 /foo/bar/bazconsole.log( path.resolve('/foo/bar', './baz') );

  // 輸出 /foo/bar/bazconsole.log( path.resolve('/foo/bar', './baz/') );

  // 輸出 /tmp/fileconsole.log( path.resolve('/foo/bar', '/tmp/file/') );

  // 輸出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path/www/js/mod.jsconsole.log( path.resolve('www', 'js/upload', '../mod.js') );

  路徑解析

  path.parse(path)

  path.normalize(filepath)

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

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

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

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

 ?。?nbsp;對(duì)路徑中的 .  .. 進(jìn)行處理。(類似于shell里的 cd .. 

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

  感覺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"

  代碼示例如下。建議讀者把代碼拷貝出來運(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源碼如下: 傳送門

  文件路徑分解/組合

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

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

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

  首先是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文檔說明后發(fā)現(xiàn),path.format(pathObject)中,pathObject的配置屬性是可以進(jìn)一步精簡(jiǎn)的。

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

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

 ?。?nbsp;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) 的反向操作,直接上官網(wǎng)例子。

  四個(gè)屬性,對(duì)于使用者是挺便利的,不過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"http:// }

  獲取相對(duì)路徑

  接口:path.relative(from, to)

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

  邊界:

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

 ?。?nbsp;如果 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)。也就是說,同樣的屬性、接口,在不同平臺(tái)上的表現(xiàn)不同。

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

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

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

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

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

  直接來例子更直觀。

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

 

文章來源:chyingp

您還未登錄,請(qǐng)先登錄

熱門帖子

最新帖子

?