• 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?');  
    }
    
  • 相关阅读:
    TCP/IP——何时用UDP代替TCP
    网络编程——客户/服务器程序设计范式
    各种常见英特网应用协议的使用情况和传输层三大协议的异同
    linux dd使用记录
    杂谈-为什么我们不要去外包公司
    小雪的成都
    哪个的情感
    mac上的git completion
    ue4 UE4Editor.lib找不到
    ue4 重新生成ide project文件的命令行
  • 原文地址:https://www.cnblogs.com/mininice/p/3875505.html
Copyright © 2020-2023  润新知