欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Node.js中路徑處理模塊path詳解

 更新時(shí)間:2016年11月14日 11:15:08   投稿:daisy  
相信大家都知道在nodejs中,path是個(gè)使用頻率很高,但卻讓人又愛(ài)又恨的模塊。因?yàn)椴糠治臋n說(shuō)的不夠清晰,還有部分因?yàn)榻涌诘钠脚_(tái)差異性。本文就給大家詳細(xì)介紹下關(guān)于Node.js中的路徑處理模塊path,希望能對(duì)大家學(xué)習(xí)或者使用模塊path有所幫助,下面來(lái)一起看看吧。

前言

在node.js中,提供了一個(gè)path某塊,在這個(gè)模塊中,提供了許多使用的,可被用來(lái)處理與轉(zhuǎn)換路徑的方法與屬性,將path的接口按照用途歸類,仔細(xì)琢磨琢磨,也就沒(méi)那么費(fèi)解了。下面我們就來(lái)詳細(xì)介紹下關(guān)于Node.js中的路徑處理模塊path。

獲取路徑/文件名/擴(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一下。這句話反正我自己看著也是莫名其妙,可以參考下面的偽代碼定義。

例子如下:

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)行處理。(類似于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.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.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ì)于使用者是挺便利的,不過(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\\']

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家學(xué)習(xí)或者使用node.js能有所幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

  • 掌握Node.js中的Promise異步編程方式

    掌握Node.js中的Promise異步編程方式

    Node.js中的Promise是一種異步編程方式,可以解決回調(diào)地獄問(wèn)題,提高代碼可讀性和可維護(hù)性。通過(guò)掌握Promise的使用方法,可以更好地進(jìn)行異步編程,避免一些常見(jiàn)的錯(cuò)誤和陷阱
    2023-05-05
  • 使用nodejs解析json數(shù)據(jù)

    使用nodejs解析json數(shù)據(jù)

    這篇文章主要介紹了使用nodejs解析json數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • Express 配置HTML頁(yè)面訪問(wèn)的實(shí)現(xiàn)

    Express 配置HTML頁(yè)面訪問(wèn)的實(shí)現(xiàn)

    這篇文章主要介紹了Express 配置HTML頁(yè)面訪問(wèn)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • node.js中的fs.readSync方法使用說(shuō)明

    node.js中的fs.readSync方法使用說(shuō)明

    這篇文章主要介紹了node.js中的fs.readSync方法使用說(shuō)明,本文介紹了fs.readSync方法說(shuō)明、語(yǔ)法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下
    2014-12-12
  • Node.js使用http模塊實(shí)現(xiàn)后臺(tái)服務(wù)器流程解析

    Node.js使用http模塊實(shí)現(xiàn)后臺(tái)服務(wù)器流程解析

    這篇文章將會(huì)教會(huì)你前端工程師怎么搭建后臺(tái)服務(wù)器,做自己的后端開(kāi)發(fā),同時(shí),在這篇文章開(kāi)始你就開(kāi)始正式進(jìn)入全棧的道路咯!本片文章將細(xì)解http模塊,在開(kāi)始前我們將復(fù)習(xí)一點(diǎn)計(jì)算機(jī)網(wǎng)絡(luò)的知識(shí)
    2022-09-09
  • npm配置國(guó)內(nèi)鏡像資源+淘寶鏡像的方法

    npm配置國(guó)內(nèi)鏡像資源+淘寶鏡像的方法

    這篇文章主要介紹了npm配置國(guó)內(nèi)鏡像資源+淘寶鏡像的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-09-09
  • 使用Express處理請(qǐng)求和托管靜態(tài)資源方式

    使用Express處理請(qǐng)求和托管靜態(tài)資源方式

    這篇文章主要介紹了使用Express處理請(qǐng)求和托管靜態(tài)資源方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • nodejs調(diào)用cmd命令實(shí)現(xiàn)復(fù)制目錄

    nodejs調(diào)用cmd命令實(shí)現(xiàn)復(fù)制目錄

    本文給大家介紹的是如何在nodejs中調(diào)用CMD命令,從而實(shí)現(xiàn)目錄的復(fù)制,非常的實(shí)用,有需要的小伙伴可以參考下。
    2015-05-05
  • Node.js Express 框架 POST方法詳解

    Node.js Express 框架 POST方法詳解

    這篇文章主要介紹了Node.js Express 框架 POST方法詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-01-01
  • 微信小程序在線客服自動(dòng)回復(fù)功能(基于node)

    微信小程序在線客服自動(dòng)回復(fù)功能(基于node)

    這篇文章主要介紹了微信小程序在線客服自動(dòng)回復(fù)功能(基于node),由于小程序嵌套webview時(shí)需要校驗(yàn)域名,因此跳轉(zhuǎn)到第三方應(yīng)用市場(chǎng)和Appstroe無(wú)法實(shí)現(xiàn)導(dǎo)流。那怎么辦呢,需要的朋友可以參考下
    2019-07-07

最新評(píng)論