zoukankan      html  css  js  c++  java
  • node & grunt path处理相关

    在nodejs平台上写一些工具或者服务, 有很多需求会涉及到对目录或者文件路径的处理和操作。整理一些常用的处理path的方法

    1、global

    __dirname

    Example: running node example.js from /Users/jiao
    console.log(__dirname);
    // /Users/jiao
    

    __filename

    Example: running node example.js from /Users/jiao
    
    console.log(__filename);
    // /Users/jiao/example.js
    

    process

    Example: running grunt buildguide from /Users/jiao/test
    process.execPath   //usr/local/bin/node
    process.env.PWD;   //Users/jiao/test
    process.cwd();     //Users/jiao/test
     
     
    //修改当前进程工作区为/Users/jiao
    process.chdir("/Users/jiao"); 
     
    process.cwd();     //Users/jiao
    process.env.PWD;   //Users/jiao/test
    

    2、node path module

    官方解释:This module contains utilities for handling and transforming file paths. Almost all these methods perform only string transformations. The file system is not consulted to check whether paths are valid.
    详情参考:http://nodejs.org/api/path.html

    path.resolve([from ...], to)

    path.resolve('/foo/bar', './baz')
    // returns
    '/foo/bar/baz'
     
    path.resolve('/foo/bar', '/tmp/file/')
    // returns
    '/tmp/file'
     
    path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
    // if currently in /home/myself/node, it returns
    '/home/myself/node/wwwroot/static_files/gif/image.gif'
    

    path.relative(from, to)

    
    path.relative('C:\orandea\test\aaa', 'C:\orandea\impl\bbb')
    // returns
    '..\..\impl\bbb'
     
    path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
    // returns
    '../../impl/bbb'
    

    path.dirname()、path.extname()、path.basename()、path.join()等

    3、grunt中和路径相关的处理

    --base参数

    会将working directory设置为Gruntfile所在的目录或--base参数所指定的目录,默认为Gruntfile所在的位置

    process.chdir(grunt.option('base') || path.dirname(gruntfile));

    grunt.file.setBase

    file.setBase = function() {
       var dirpath = path.join.apply(path, arguments);
       process.chdir(dirpath);
    };
    grunt.loadNpmTasks(p)
    

    插件的加载路径默认是当前工作目录下面的 node_modules + p + 'tasks', 查看grunt内部的代码实现如下:

    var root = path.resolve('node_modules');
    var tasksdir = path.join(root, p, 'tasks');
     
    //加载grunt 插件的tasks
    if (grunt.file.exists(tasksdir)) {
        loadTasks(tasksdir);
    } else {
        grunt.log.error('Local Npm module "' + name + '" not found. Is it installed?');  
    }
    
  • 相关阅读:
    Tidy 一个把HTML 转成XHTML的工具库[整理]
    HTTP详解(转载)
    C#中各种验证方法(数字,邮件,电话,传真,邮政编码,网络地址)和自动编号的
    常用Visual C# 快捷键
    c#中字符串截取使用的方法
    C#将相片转换成二进制存储在数据库中,再从数据库中显示出来
    用长按键重复输入 Mac OS X Lion
    Unsupported major.minor version 51.0解决办法
    XCode4.3.2 没有Command Line Utility选项
    IBM高级工程师,谷歌等国际知名公司工程师撰写Android开发教程合集
  • 原文地址:https://www.cnblogs.com/mininice/p/3875505.html
Copyright © 2011-2022 走看看