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?');  
    }
    
  • 相关阅读:
    nodeJS入门01-http模块
    nodeJS入门-Buffer对象
    php与MySQL(php内置mysql函数)
    php与MySQL(基本操作)
    log4net
    js验证小数类型(浮点数)和整数类型
    牛腩学ASP.NET CORE做博客视频
    opencv再学习之路(八)---设定感兴趣区域(RIO)
    opencv再学习之路(四)---色彩分割得到二值图像
    opencv再学习之路(三)---形态学操作
  • 原文地址:https://www.cnblogs.com/mininice/p/3875505.html
Copyright © 2011-2022 走看看