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?');  
    }
    
  • 相关阅读:
    shell脚本积累
    while,shift,until,case
    条件测试命令,if命令,双圆括号,双中括号
    seq命令,tr命令,sort命令,cut命令
    正则,grep命令详解
    Ansible实现批量管理服务器
    实时同步服务知识梳理
    RHEL7破解密码操作步骤
    运维核心基础知识之——MD5sum校验文件
    Linux运维基础提高之RAID卡和磁盘分区
  • 原文地址:https://www.cnblogs.com/mininice/p/3875505.html
Copyright © 2011-2022 走看看