nodejs直接调用grunt,非调用批处理

在windows下,我们做js构建工作,都习惯安装grunt-cli,只需要命令行grunt。。。一切构建工作都自动完成了。这已经是很完美的情况了,不过最近要做一个服务器版的自动化构建系统,在nodejs中调用批处理执行grunt就显得很矬,而且各种问题。是否有更好,更漂亮的方式呢?

grunt本来就是nodejs程序,安装后表现为一个node_module,那么cli是什么呢?这只是一个nodejs写的命令行界面。所以,nodejs肯定可以直接在js层面调用grunt。

我们需要做的,只需要揭开cli的面纱。

首先,看看cli安装后的位置:

(win7)

C:\Users\kenkozheng\AppData\Roaming\npm\node_modules\grunt-cli

cli主要代码是一堆参数判断处理,但最终实际关键点是grunt.cli( )

#!/usr/bin/env node

'use strict';

process.title = 'grunt';

// Especially badass external libs.
var findup = require('findup-sync');
var resolve = require('resolve').sync;

// Internal libs.
var options = require('../lib/cli').options;
var completion = require('../lib/completion');
var info = require('../lib/info');
var path = require('path');


var basedir = process.cwd();
var gruntpath;

// Do stuff based on CLI options.
if ('completion' in options) {
  completion.print(options.completion);
} else if (options.version) {
  info.version();
} else if (options.base && !options.gruntfile) {
  basedir = path.resolve(options.base);
} else if (options.gruntfile) {
  basedir = path.resolve(path.dirname(options.gruntfile));
}

try {
  gruntpath = resolve('grunt', {basedir: basedir});
} catch (ex) {
  gruntpath = findup('lib/grunt.js');
  // No grunt install found!
  if (!gruntpath) {
    if (options.version) { process.exit(); }
    if (options.help) { info.help(); }
    info.fatal('Unable to find local grunt.', 99);
  }
}

// Everything looks good. Require local grunt and run it.
require(gruntpath).cli();

那么我们回到自己的nodejs项目中,先安装好grunt模块,然后在js代码中轻轻写上两句:

var grunt = require('grunt');
console.log(grunt.cli);
grunt.cli({
    gruntfile: __dirname + '/applications/5/check_out/Gruntfile.js'
});

一切就搞掂了,非常顺利。

不过,这里有个小坑,折腾了kenko一点时间,就是gruntfile必须是绝对路径,不能是相对路径。

最后,不得不赞一下grunt的代码。如果我们不懂cli的参数,只需要console.log(grunt.cli),这不是冷冰冰的输出function(){xxxx},而是一份参数说明!!!不得不佩服作者的用心良苦。