[Node.js] path 模組 – 將字串路徑給規範化

有時可能會在定義好的路徑中不小心加上多餘的字元,當成路徑錯誤,可使用 path.normalize() 來避免此類錯誤。

使用 path.normalize() 將字串路徑給規範化

var path = require('path'); // 引入路徑處理模組

var path_a = "/home//king";
console.info(path.normalize(path_a)); /home/king

var path_b = "/home//king/";
console.info(path.normalize(path_b)); /home/king/

var path_c = "/home///king//";
console.info(path.normalize(path_c)); /home/king/

var path_d = "/home/king/.";
console.info(path.normalize(path_d)); /home/king

var path_e = "/home/king//.";
console.info(path.normalize(path_e)); /home/king

var path_f = "/home/king//.abc";
console.info(path.normalize(path_f)); /home/king/.abc

var path_g = "/home/king//..";
console.info(path.normalize(path_g)); /home

var path_h = "/home/king//..abc";
console.info(path.normalize(path_h)); /home/king/..abc

var path_i = "/home/king/../..";
console.info(path.normalize(path_i)); /

var path_j = "/home/king//..//..";
console.info(path.normalize(path_j)); /

您可在此處留言

搶先留言!

Notify of
avatar
wpDiscuz