nodejs 路徑處理

https://blog.csdn.net/liudongdong19/article/details/81353159

獲取 /路徑/文件名/擴展名
獲取路徑:path.dirname(filepath)
獲取文件名:path.basename(filename)
獲取擴展名:path.extname(filepath)
獲取所在路徑

const path=require("path");
var filepath='/node/base/path/test.js';
console.log(
    path.dirname(filepath)
)
//輸出/node/base/path
獲取文件名 
path.basename(filepath)實際上是獲取了路徑的最後一部分, 
而不是真正的獲取到了文件名,但是在實際應用中最後的字符往往就是我們的文件名

const path = require("path");
console.log(path.basename("/node/base/path/test.js"));
//輸出    test.js
console.log(path.basename("/node/base/path/test/"));
//輸出    test
console.log(path.basename("/node/base/path/test"));
//輸出    test
如果只想獲取文件名,不需要擴展名則可以使用第二個參數,第二個參數就是指定的文件擴展名

const path = require("path");
console.log(path.basename("/node/base/path/test.js",".js"));
//輸出    test
獲取文件擴展名

const path = require("path");
console.log(path.extname("/node/base/path/test.js",".js"));
//輸出    .js
更詳細的規則是如下:(假設 path.basename(filepath) === B )

從B的最後一個.開始截取,直到最後一個字符。
如果B中不存在.,或者B的第一個字符就是.,那麼返回空字符串。
下面是官方手冊的一個案例

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]) 
接收多個路勁字符串參數,把路徑參數拼接起來然後再執行一下normalize

例子如下

const path=require("path");
path.join("/temp",'node','/js/test.js')
//輸出    \temp\node\js\test.js
path.join("/temp",'node','/js/test.js/','..')
//輸出    \temp\node\js
path定義的僞代碼如下:

module.exports.join = function(){
  var paths = Array.prototye.slice.call(arguments, 0);
  return this.normalize( paths.join('/') );
};
path.resolve([…paths]) 
這個接口的作用就相當於在shell命令下,從左到右運行一遍cd path命令, 
最終獲取的絕對路徑/文件名,就是這個接口所返回的結果了。

比如

path.resolve(‘/temp/node’, ‘./test’)

可以看成下面命令的結果

cd /temp/node
cd ./test
更多的例子如下
var path = require('path');
 
// 假設當前工作路徑是 /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.normalize(filepath) 
從官方文檔的描述來看,path.normalize(filepath) 應該是比較簡單的一個API,不過用起來總是覺得沒底。

爲什麼呢?API說明過於簡略了,包括如下:

如果路徑爲空,返回.,相當於當前的工作路徑。
將對路徑中重複的路徑分隔符(比如linux下的/)合併爲一個。
對路徑中的. 、..進行處理。(類似於shell裏的cd ..)
如果路徑最後有/,那麼保留該/。
代碼示例如下。建議讀者把代碼拷貝出來運行下,看下實際效果。

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('路徑結尾是否帶/', 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('重複的/', 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('相對路徑', 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屬性,按照一定的規則,組合成一個文件路徑。
path.parse(filepath):path.format()方法的反向操作。
我們先來看看官網對相關屬性的說明。

首先是linux下

然後是windows下 


path.format(pathObject) 
閱讀相關API文檔說明後發現,path.format(pathObject)中,pathObject的配置屬性是可以進一步精簡的。

根據接口的描述來看,以下兩者是等價的。

root vs dir:兩者可以互相替換,區別在於,路徑拼接時,root後不會自動加/,而dir會自動加/。
base vs name+ext:兩者可以互相替換。
例子如下

const path = require("path");
//root+base
var p1 = {
    root: "/temp/",
    base: "test.js"
}
path.format(p1)  //輸出   /temp/test.js
//dir+name+ext
var p2 = {
    dir: "/temp",
    name: 'test',
    ext: '.js'
}
path.format(p2) //輸出    /temp/test.js
path.parse(filepath) 
path.format(pathObject) 的反向操作,也就是把一個路徑轉換爲具有 root/dir/name/ext/base 等屬性的對象

以下是官方給出的例子:

path.parse('/home/user/dir/file.txt')
// returns
// {
//    root : "/",
//    dir : "/home/user/dir",
//    base : "file.txt",
//    ext : ".txt",
//    name : "file"
// }
獲取相對路徑
接口:path.relative(from, to)

描述:The path.relative() method returns the relative path from from to to (從from路徑,到to路徑的相對路徑。)

邊界:

如果from、to指向同個路徑,那麼,返回空字符串。
如果from、to中任一者爲空,那麼,返回當前工作路徑。
例子如下:

const 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);  
// 輸出 ..\..\Study\Nodejs\mycode\path
平臺相關接口/屬性
以下屬性、接口,都跟平臺的具體實現相關。也就是說,同樣的屬性、接口,在不同平臺上的表現不同。

path.posix:path相關屬性、接口的linux實現。
path.win32:path相關屬性、接口的win32實現。
path.sep:路徑分隔符。在linux上是/,在windows上是\。
path.delimiter:path設置的分割符。linux上是:,windows上是;。
注意,當使用 path.win32 相關接口時,參數同樣可以使用/做分隔符,但接口返回值的分割符只會是\。

例子如下:

> 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系統例子:

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系統例子:

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\\']
const這個關鍵字是ES6裏面定義的常量,不可改變。

1 const url = require("url");
  url一共提供了三個方法,分別是url.parse();  url.format();  url.resolve();

  1 url.parse(urlString,boolean,boolean)

  parse這個方法可以將一個url的字符串解析並返回一個url的對象

  參數:urlString指傳入一個url地址的字符串

     第二個參數(可省)傳入一個布爾值,默認爲false,爲true時,返回的url對象中,query的屬性爲一個對象。

     第三個參數(可省)傳入一個布爾值,默認爲false,爲true時,額,我也不知道有什麼不同,可以去看看API。

 

 

例子1,url.parse只傳一個參數的情況。

 1 url.parse("http://user:[email protected]:8080/p/a/t/h?query=string#hash");
 2 /*
 3 返回值:
 4 {
 5   protocol: 'http:',
 6   slashes: true,
 7   auth: 'user:pass',
 8   host: 'host.com:8080',
 9   port: '8080',
10   hostname: 'host.com',
11   hash: '#hash',
12   search: '?query=string',
13   query: 'query=string',
14   pathname: '/p/a/t/h',
15   path: '/p/a/t/h?query=string',
16   href: 'http://user:[email protected]:8080/p/a/t/h?query=string#hash'
17  }
18 沒有設置第二個參數爲true時,query屬性爲一個字符串類型
19 */


例子2,url.parse第二個參數爲true的情況

 

 1 url.parse("http://user:[email protected]:8080/p/a/t/h?query=string#hash",true);
 2 /*
 3 返回值:
 4  {
 5   protocol: 'http:',
 6   slashes: true,
 7   auth: 'user:pass',
 8   host: 'host.com:8080',
 9   port: '8080',
10   hostname: 'host.com',
11   hash: '#hash',
12   search: '?query=string',
13   query: { query: 'string' },
14   pathname: '/p/a/t/h',
15   path: '/p/a/t/h?query=string',
16   href: 'http://user:[email protected]:8080/p/a/t/h?query=string#hash'
17  }
18 返回的url對象中,query屬性爲一個對象
19 */
 

  2 url.format(urlObj)

  format這個方法是將傳入的url對象編程一個url字符串並返回

  參數:urlObj指一個url對象

 

例子3,url.format

url.format({
    protocol:"http:",
    host:"182.163.0:60",
    port:"60"
});
/*
返回值:
'http://182.163.0:60'
*/
  3 url.resolve(from,to)

  resolve這個方法返回一個格式爲"from/to"的字符串,在寶寶看來是對傳入的兩個參數用"/"符號進行拼接,並返回

console.info("------   url parse()   ------");
console.info();
var url = require('url');// TODO: 引入路徑處理模塊
/**
 * 測試 url.resolve() 函數方法
 * @type {string}
 */
console.info(url.resolve('/one/two/three', 'four'));
console.info(url.resolve('/one/two/three/', 'four'));
console.info(url.resolve('/one/two/three', '/four'));
console.info(url.resolve('/one/two/three/', '/four'));
console.info(url.resolve('http://www.example.com/one', 'two'));
console.info(url.resolve('http://www.example.com/one', '/two'));
console.info(url.resolve('http://www.example.com/one/', 'two'));
console.info(url.resolve('http://www.example.com/one/', '/two'));
/one/two/four
/one/two/three/four
/four
/four
http://www.example.com/two
http://www.example.com/two
http://www.example.com/one/two
http://www.example.com/two
1 querystring.parse(str,separator,eq,options)

parse這個方法是將一個字符串反序列化爲一個對象。

參數:str指需要反序列化的字符串;

   separator(可省)指用於分割str這個字符串的字符或字符串,默認值爲"&";

   eq(可省)指用於劃分鍵和值的字符或字符串,默認值爲"=";

   options(可省)該參數是一個對象,裏面可設置maxKeys和decodeURIComponent這兩個屬性:

      maxKeys:傳入一個number類型,指定解析鍵值對的最大值,默認值爲1000,如果設置爲0時,則取消解析的數量限制;

      decodeURIComponent:傳入一個function,用於對含有%的字符串進行解碼,默認值爲querystring.unescape。在官方API的例子中,使用gbkDecodeURIComponent這個方法會報錯,顯示gbkDecodeURIComponent is no defined,這是因爲在使用這個gbkDecodeURIComponent這個方法之前需要先進行定義。在API中也寫了Assuming gbkDecodeURIComponent function already exists...這句話的意思是”假設這個gbkDecodeURIComponent方法已經存在”。

例子1,querystring.parse

 1 querystring.parse("name=whitemu&sex=man&sex=women");
 2 /*
 3 return:
 4 { name: 'whitemu', sex: [ 'man', 'women' ] }
 5 */
 6 querystring.parse("name=whitemu#sex=man#sex=women","#",null,{maxKeys:2});
 7 /*
 8 return:
 9 { name: 'whitemu', sex: 'man' }
10 */


2 querystring.stringify(obj,separator,eq,options)

stringify這個方法是將一個對象序列化成一個字符串,與querystring.parse相對。

參數:obj指需要序列化的對象

   separator(可省)用於連接鍵值對的字符或字符串,默認值爲"&";

   eq(可省)用於連接鍵和值的字符或字符串,默認值爲"=";

   options(可省)傳入一個對象,該對象可設置encodeURIComponent這個屬性:

      encodeURIComponent:值的類型爲function,可以將一個不安全的url字符串轉換成百分比的形式,默認值爲querystring.escape()。

例子2,querystring.stringify

querystring.stringify({name: 'whitemu', sex: [ 'man', 'women' ] });
/*
return:
'name=whitemu&sex=man&sex=women'
*/
querystring.stringify({name: 'whitemu', sex: [ 'man', 'women' ] },"*","$");
/*
return:
'name$whitemu*sex$man*sex$women'
*/


3 querystring.escape(str)

escape可使傳入的字符串進行編碼

例子3,querystring.escape

querystring.escape("name=慕白");
/*
return:
'name%3D%E6%85%95%E7%99%BD'
*/
4 querystring.unescape(str)

unescape方法可將含有%的字符串進行解碼

例子4,querystring.unescape

querystring.unescape('name%3D%E6%85%95%E7%99%BD');
/*
return:
'name=慕白'
*/
總結:

  querystring這個模塊相對的還是比較簡單,僅有4個方法。

  querystring.stringify序列化;

  querystring.parse反序列化;

  querystring.escape編碼;

  querystring.unescape解碼;
————————————————
版權聲明:本文爲CSDN博主「liudongdong19」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/liudongdong19/article/details/81353159

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章