node.js – gulp.js – 如何将多个流返回主流?

我想启动一个gulp.src流,将其传递给一个创建一堆新流的函数,然后将其结果传递给gulp.dest.下面是我到目前为止,但它显然没有工作,因为我正在将流回流到gulp.dest,因为它期待一个文件,而不是流.所以我的问题是:如何正确地将n个流返回到gulp的原始流中,以便它们能够在管道中正确地继续下去?

//gulpfile.js
var gulp = require('gulp'),bundle = require('./lib/bundle.js');

gulp.task('bundle',function() {
  return gulp.src('./bundle.config.js')
    .pipe(bundle())
    .pipe(gulp.dest('./public'));
});

//bundle.config.js
module.exports = {
  bundle: {
    main: {
      js: [
        './content/js/foo.js','./content/js/baz.js'
      ],css: [
        './content/**/*.css'
      ],resources: './content/**/*.{png,svg}'
    },other: {
      js: './content/js/other.js',css: '',resources: ''
    }
  }
};

//bundle.js
var gulp = require('gulp'),through = require('through2'),concat = require('gulp-concat');

module.exports = function () {
  return through.obj(function (file,enc,cb) {
    var config;
    try {
      config = require(file.path); // get config file
    } catch (e) {
      this.emit('error',e);
      return cb();
    }
    var streams = [];
    for (var key in config.bundle) {
      var bundle = config.bundle[key];

      streams.push(
        gulp.src(bundle.js,{base: '.'})
          .pipe(concat(key + '.js'))
      );

      streams.push(
        gulp.src(bundle.css,{base: '.'})
          .pipe(concat(key + '.css'))
      );

      streams.push(
        gulp.src(bundle.resources,{base: '.'})
        //.pipe(something())
      );

    }
    for (var i = 0; i < streams.length; i++) {
      // This causes an error in `gulp.dest` because we're returning the stream,not the file.
      // Instead,how do I resolve each of the individual streams and push the results back to the main stream??
      this.push(streams[i]);
    }
    cb();
  });
};

你可以看到这个代码,你可以在这个repo:https://github.com/chmontgomery/gulp-streams-to-stream上分叉和玩

解决方法

您可以使用 merge-stream连接流

var gulp = require('gulp');
var merge = require('merge-stream');

gulp.task('bundle',function () {

  var paths = [
    { src: 'src/admin/**',dest: './build/admin' },{ src: 'src/public/**',dest: './build' }
  ];

  var tasks = paths.map(function (path) {
    return gulp.src(path.src).pipe(gulp.dest(path.dest));
  }

  return merge(tasks);
};

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...