Node之文件路径处理模块:path模块

Node之文件路径处理模块:path模块

文件路径用来表示具体的文件,可分为绝对路径和相对路径,本文介绍的就是Node中的path模块,利用path模块可以实现提取文件名信息,检测文件是否存在等操作。

模块引入:

var path = require('path');

有关方法:

path.normalize() ,规范化路径字符串,而且还能处理 . , 、 , //

path.join() ,连接任意多个路径字符串,需要将所有路径字符串依次传递给join作为参数,同时也会对路径进行规范化。

path.resolve() , 将多个路径解析为一个规范化的绝对路径。

path.relative() , 确定如何从一个绝对路径跳转到另一个绝对路径。

path.dirname() , 获取文件路径的目录部分。

path.basename() , 从文件路径提取文件名。

path.extname() , 获取文件扩展名。

path.exits() , 判断给定的文件路径是否存在,但是Node 0.8用 fs.exists代替了 path.exists。

使用示例:

    //path.js : 本例存储路径在F盘的path文件夹下,即: F:\path

    var path = require('path');

    var result1 = path.normalize('/foo/bar//baz/asdf../quex..');
    console.log("result1: " + result1); // result1: foo\bar\baz\asdf..\ques..

    var result2 = path.join('/one', 'two', 'three/four', 'five' , '..');
    console.log("result2: " + result2); // result2: one\two\three\four

    var result3 = path.resolve('one/two', './three');
    console.log("result3: " + result3); // result3: F:\path\one\two\three 
    var result4 = path.resolve('one/two', '/three/four');
    console.log("result4: " + result4); // result4: F:\three\four
    var result5 = path.resolve('/one/two', 'static_files/png', '../gif/image.gif');
    console.log("result5: " + result5); // result5: F:\one\two\static_files\gif\image.gif

    var result6 = path.relative('one/two/test/aaa', 'one/two/example/bbb');
    console.log("result6: " + result6); // ..\..\example\bbb

    var result7 = path.dirname('/one/two/three/test.txt');
    console.log('result7: ' + result7); // one\two\three

    var result8 = path.basename('/one/two/three/test.txt');
    console.log('result8: ' + result8); // test.txt
    var result9 = path.basename('/one/two/three/test.txt', '.txt');
    console.log('result9: ' + result9); // test

    var result10 = path.extname('/a/b/index.html');
    console.log('result10: ' + result10); // .html
    var result11 = path.extname('/a/b/index');
    console.log('result11: ' + result11); // (空白)
    var result12 = path.extname('/a/b/.');
    console.log('result12: ' + result12); // (空白)
    var result13 = path.extname('/a/b/index.');
    console.log('result13: ' + result13); // .


    // node 0.8 用fs.exists 代替了 path.exists
    var fs = require('fs');
    fs.exists('./path.js', function(exists){
    console.log('exists: ',exists); // exists: true
    });
    fs.exists('./does_not_exist', function(exists){
    console.log('exists: ',exists); // exists: false
    });

运行结果:

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

英子的搬砖日志

您的鼓励是我创作的动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值