欢迎来到3672js教程,我们关注js教程、js框架、js代码特效等。

node path的使用详解,

3672Js.Com2022-11-09 00:13 来源:未知 阅读:5742 关注度2

node path的使用详解,


目录
  • path使用
    • path.join()
    • path.basename(p[, ext])
    • fs使用
  • node.js 中内置模块 path模块的基本使用

    path使用

    path.join()

    使用path.join()方法,可以把多个路径片段拼接为完整的路径字符串

    const path=require('path')
    // 使用path.join()方法,可以把多个路径片段拼接为完整的路径字符串
    //1. ../会抵消前面的路径
     const pathStr= path.join('/a','/b/c','../','./d')
    console.log(pathStr)
    // 2.使用__dirname方法
    const pathStr2=path.join(__dirname,'./files/1.txt')
    console.log(pathStr2);//输出当前文件所处目录/files/1.txt

    输出效果

    path.basename(p[, ext])

    方法可以从一个文件路径中获取到文件的名称部分

    const path=require('path')
    //定义文件的存放路径
    const fpath='/files/index.html'
    const fullName=path.basename(fpath)//获取完整的文件名
    console.log(fullName);//index.html
    const nameWithoutExt=path.basename(fpath,'.html')//移除扩展名
    console.log('nameWithoutExt',nameWithoutExt);

    path.extname(p)

    返回路径中文件的后缀名,即路径中最后一个'.'之后的部分。如果一个路径中并不包含'.'或该路径只包含一个'.' 且这个'.'为路径的第一个字符,则此命令返回空字符串。

    const path=require('path')
    // 使用path.extname()方法可以获取路径中的扩展名部分
    const fpath='files/index.html'
    const fext=path.extname(fpath)
    console.log(fext);

    fs使用

    const fs=require('fs');
    const path = require('path');
    // 读取文件 fs.readFile
    fs.readFile(path.join(__dirname,'/files/1.txt'),'utf-8',function (err,dataStr) {
      if(err){
        return console.log('读取错误',err)
      }
      console.log('读取成功',dataStr);
    })
    console.log(text);

    node.js 中内置模块 path模块的基本使用

    //node加载文件是同步执行的 执行代码会被阻塞
    //加载过后的模块会被缓存 ,加载过后的模块module里面的loaded会变为true
    
    //node 使用的加载方式是深度优先
    
    // 一
    // const path = require('path')
    
    // const basePath = '/user/stu';
    // const filename = 'hu.text'
    
    // const p = path.resolve(basePath,filename)
    // console.log(p);
    
    
    // 二
    // const path = require('path')
    // const basepath ='./user/stu'
    // const filename = 'hu.text'
    
    // const name =  path.resolve(basepath,filename)
    // const name2 = path.join(basepath,filename)
    // path.resolve 不只是会对路径/的转化,还会对..或者.进行转化
    // path.join 只会对路径中的/进行转化
    // console.log(name);
    // console.log(name2);
    
    
    // 三
    // const path = require('path')
    // const basepath ='./user/stu'
    // const filename = 'hu.text'
    
    // const name =  path.resolve(basepath,filename)
    // console.log(path.dirname(name));//获取路径文件夹
    // console.log(path.extname(name));//获取路径的扩展名
    // console.log(path.basename(name));//获取文件的名字包括扩展名
    

    到此这篇关于node path的使用的文章就介绍到这了,更多相关node path的使用内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!

    您可能感兴趣的文章:
    • node.js中的fs.realpath方法使用说明
    • node.js中的path.basename方法使用说明
    • node.js中的path.dirname方法使用说明
    • node.js中的path.join方法使用说明
    • node.js中的path.resolve方法使用说明

    本站文章为3672js教程网友分享投稿,版权归原作者,欢迎任何形式的转载,但请务必注明出处。同时文章内容如有侵犯了您的权益,请联系我们处理。
    评论已被关闭
    {dede:include filename="foot.htm"/}