将 GULP 与 node.js 整合

Integrating GULP with node.js

我在 node.js 中有一个项目,我想在 GULP 中自动执行一些备份和修订任务。

我能够在终端中成功测试以下 gulp 代码并且一切正常。当我从 node.js 代码 运行 gulp 任务时出现问题。

Gulp代码:

var gulp = require('gulp');
var runSequence = require('run-sequence');
var rev = require('gulp-rev');
var format = require('date-format');

var dt = (new Date());
var gBkup = __dirname + '/backup/' + format.asString('ddMMyyyy_hhmm', dt);
var config = __dirname + '/gHelper.json', mnf = __dirname + '/rev-manifest.json';

var cssSrc = [], cssSrcO = [], cssSrcI = [];
var dirSrc = [], dirSrcO = [], dirSrcI = [];

gulp.task('init', function (){      // Initialize paths and all arrays containing file paths
    var fexists = require('file-exists');
    //console.log('Config exists: ' + fexists(config));
    if (fexists(config)) {
        config = require(config);
    }

    //console.log('Config object: ' + config);

    if (fexists(mnf)) {
        mnf = require(mnf);
    }

    for (var file in config.revision.ext_css) {
        var fnm = __dirname + '/preview/' + config.revision.ext_css[file];
        cssSrc.push(fnm);

        if (mnf[config.revision.ext_css[file]] != "") {
            var hnm = __dirname + '/live/' + mnf[config.revision.ext_css[file]];
            cssSrcO.push(hnm);
            console.log("Manifest: " + hnm);
        }
    }

    for (var dir in config.revision.dir) {
        dirSrc.push(__dirname + '/preview/' + config.revision.dir[dir]);
        var dirnm = __dirname + '/live/' + config.revision.dir[dir];
        dirnm = dirnm.substr(0, dirnm.length-3);
        dirSrcO.push(dirnm);
        console.log("Directory: " + dirnm);
    }

    // Files and directories will be ignored in revision
    for (var file in config.revision.ext_css) {
        cssSrcI.push('!' + __dirname + '/preview/' + config.revision.ext_css[file]);
    }

    for (var dir in config.revision.dir) {
        dirSrcI.push('!' + __dirname + './preview/' + config.revision.dir[dir]);
    }

    //console.log('Ignore CSS: ' + cssSrcI);
    //console.log('Ignore DIR: ' + dirSrcI);
});

// Revisioning Files
gulp.task('revisionCSS', function() {       // Revise CSS scripts
  var cssDest = __dirname + config.revision.ext_css_dest;

  console.log('cssDestination: ' + cssDest);
  return gulp.src(cssSrc)
        .pipe(rev())
        .pipe(gulp.dest(cssDest))
        .pipe(rev.manifest({base: cssDest, merge: true}))
        .pipe(gulp.dest(cssDest))
});

gulp.task('revInnerScripts', function () {  // Revise javascripts
  var dirDest = __dirname + config.revision.ext_dir_dest;
  var cssDest = __dirname + config.revision.ext_css_dest;

  console.log('dirInner: ' + dirDest);
  console.log('cssInner: ' + cssDest);

  return gulp.src(dirSrc)
        .pipe(rev())
        .pipe(gulp.dest(dirDest))
        .pipe(rev.manifest({base: cssDest, merge: true}))
        .pipe(gulp.dest(cssDest));
});

gulp.task('copyIgnoreRevision', function() {    // Simply copy other/ignored files from array
    var src = [__dirname + '/preview/**']
    src = src.concat(cssSrcI);
    src = src.concat(dirSrcI);
    console.log(src)

    return gulp.src(src)
    .pipe(gulp.dest(__dirname + '/live'));
});

gulp.task('removeLive', function(callback) {    // Removing files
    var del = require('del');
    var src = cssSrcO.concat(dirSrcO);
    console.log("Removing Files: " + src);
    return del(src);
});

gulp.task('backupLive', function() {            // Backing up revision files before taking revision
//  var src = ['./Live/**'];
    gulp.src(cssSrcO).pipe(gulp.dest(gBkup));

    return gulp.src(dirSrcO).pipe(gulp.dest(gBkup + "/js"));;
/*  return gulp.src(cssSrcO, {read: false})
        .pipe(clean());*/

});

gulp.task('backup', function(callback) {        // Backup tasks list
    runSequence('backupLive', 'removeLive', callback);
});
gulp.task('revise', ['copyIgnoreRevision', 'revisionCSS', 'revInnerScripts']);
gulp.task('revback', function (callback) {
    runSequence('init', 'backup', 'revreplace', callback);
});

// Replacing references
gulp.task('revreplace', ['revise'], function(callback) {        // In callback replace references for revised files
    var revReplace = require('gulp-rev-replace');
    var mReps = gulp.src(__dirname + '/rev-manifest.json');
    return gulp.src(__dirname + '/preview/*.html')
        .pipe(revReplace({manifest: mReps}))
        .pipe(gulp.dest(__dirname + '/live'));
});

gHelper.json:列出需要修改的文件。其他所有内容都将复制到目标目录。

{
  "revision": {
    "ext_css" : [
        "extie.css",
        "responsive.css",
        "style.css"
    ],
    "ext_css_dest": "/live",
    "dir": [
        "js/*.js"
    ],
    "ext_dir_dest": "/live/js"
  }
}

基本文件夹结构

MainFolder/
  gHelper.json
  gulpfile.js
  preview/
    HTML files which contains references to revision files
    Revision files (CSS and JS). CSS files are mentioned in gHelper.json
    js/
        Revision files (mainly js) which are to be revised as this folder is mentioned in gHelper.json and all files from the folder will be revised

当调用 gulp 任务 revback 时,将生成文件夹 live 并将其添加到 MainFolder 中。再次调用 revback 时,首先会生成 backup/{timestamp} 文件夹,仅备份修改后的文件,然后对 live 文件夹进行修改。

让我们看看 来自 Node.js 的代码:

/* 发布客户端 */

var gulp = require('gulp');
router.post('/api/:clientName/publish', function(req, res, next) {
    var clientName = req.params.clientName;
    var filePath = '/gulpfile'; // Full path for gulp file

    console.log("Publish client: " + filePath);
    try {
      var gtask = require(filePath);

      if (gulp.tasks.revback) {
          console.log('gulp file contains task!');
          gulp.start('revback');
      }
    } catch (err) {
      return console.error(err);
    }
});

现在问题来了,有时 gulp 任务没有完成,rev-manifest.json 没有在正确的位置创建意味着在 MainFolder 里面但是在这个文件夹的外面创建node.js 谎言。

请告诉我如何解决这个问题,谢谢。


以下是rev-manifest.json的内容:

{
  "dctConf.js": "dctConf-7c467cb7cb.js",
  "extie.css": "extie-a8724bfb0c.css",
  "responsive.css": "responsive-76492b9ad4.css",
  "style.css": "style-770db73beb.css",
  "translation.js": "translation-9687245bfb.js"
}

您可以尝试将 gulpfile.js 中的工作目录更改为 gulpfile 的位置。只需在顶部添加这个

process.chdir(__dirname);

文档

我使用了 gulp 的原生回调并删除了 运行-sequence 模块。

例如:

gulp.task('revback', ['revise'], function(callback) {
    var revReplace = require('gulp-rev-replace');
    var mReps = gulp.src(__dirname + '/rev-manifest.json');

    console.log('Manifest content: ' + mReps + ' && ' + __dirname + '/rev-manifest.json');

    return gulp.src(__dirname + '/preview/*.html')
        .pipe(revReplace({manifest: mReps}))
        .pipe(gulp.dest(__dirname + '/live'))
        .once('error', function(e) {
            console.log('Error at revback: ' + e);
            callback(e);
            process.exit(1);
        })
        .once('end', function() {
            console.log('Ending process at revback!');
            callback();
            process.exit();
        });
});

gulp.task('revise', ['copyIgnoreRevision', 'revisionCSS', 'revInnerScripts']);

gulp.task('backupLive', ['init'], function() {
//  var src = ['./Live/**'];
    gulp.src(cssSrcO).pipe(gulp.dest(gBkup));

    return gulp.src(dirSrcO).pipe(gulp.dest(gBkup + "/js"));
/*  return gulp.src(cssSrcO, {read: false})
        .pipe(clean());*/

});

这样,反向链接到 init 函数。