zoukankan      html  css  js  c++  java
  • 小tips:path的join和resolve的使用区别

    1.连接路径:path.join([path1][, path2][, ...])

    path.join()方法可以连接任意多个路径字符串。要连接的多个路径可做为参数传入。

    path.join()方法在接边路径的同时也会对路径进行规范化。例如:

    var path = require('path'); 
    //合法的字符串连接 
    path.join('/foo', 'bar', 'baz/asdf', 'quux', '..') 
    // 连接后 
    '/foo/bar/baz/asdf' 
    
    //不合法的字符串将抛出异常 
    path.join('foo', {}, 'bar') 
    // 抛出的异常 TypeError: Arguments to path.join must be strings'

    2.路径解析:path.resolve([from ...], to)

    path.resolve()方法可以将多个路径解析为一个规范化的绝对路径。其处理方式类似于对这些路径逐一进行cd操作,与cd操作不同的是,这引起路径可以是文件,并且可不必实际存在(resolve()方法不会利用底层的文件系统判断路径是否存在,而只是进行路径字符串操作)。例如:

    path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')

    相当于

    cd foo/bar
    cd /tmp/file/
    cd ..
    cd a/../subfile
    pwd

    例子:

    path.resolve('/foo/bar', './baz') 
    // 输出结果为 
    '/foo/bar/baz' 
    path.resolve('/foo/bar', '/tmp/file/') 
    // 输出结果为 
    '/tmp/file' 
    
    path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif') 
    // 当前的工作路径是 /home/itbilu/node,则输出结果为 
    '/home/itbilu/node/wwwroot/static_files/gif/image.gif'

    3.对比

    const path = require('path'); 
    let myPath = path.join(__dirname,'/img/so'); 
    let myPath2 = path.join(__dirname,'./img/so'); 
    let myPath3 = path.resolve(__dirname,'/img/so'); 
    let myPath4 = path.resolve(__dirname,'./img/so'); 
    console.log(__dirname); //D:myProgram	est 
    console.log(myPath); //D:myProgram	estimgso 
    console.log(myPath2); //D:myProgram	estimgso 
    console.log(myPath3); //D:imgso<br> 
    console.log(myPath4); //D:myProgram	estimgso
  • 相关阅读:
    easy-animation | Animation for Sass
    UC手机浏览器(U3内核)相关文档整理
    视差滚动(Parallax Scrolling)的一点小心得
    MVC Filter 返回json格式
    Jquery 实现左右两侧菜单添加、移除
    .Net 发送邮件
    Request.From,Request.QueryString转对象
    DataTable转List,转对象
    SQL Table 自动生成Net底层-控制器Autofac注入
    SQL Table 自动生成Net底层-生成业务层Service
  • 原文地址:https://www.cnblogs.com/moqiutao/p/8523955.html
Copyright © 2011-2022 走看看