How to replace in stream using Gulp?

2019-04-28 20:34发布

I try to switch from Grunt to Gulp and I have an issue:

I read two streams from two files

var fileStream = gulp.src(file);
var injectionStream = gulp.src(injection)
.pipe(replace('#class-name#', argv.cname));

If my console argument "--remove" is absent I have no problem to concatenate these streams

.pipe(concat('animation.styl'))
.pipe(gulp.dest('./dist'))

However when '--remove' is true I want to delete injection, in other words, subtract injectionStream from fileStream.

I tried:

var es = require('event-stream');
es.replace()

var replace = require('gulp-replace');

It works with strings, but I cannot succeed with streams read from files. Can anybody give me a small hint?

And maybe it is an incorrect tool for generation task and I should stay with Grunt and\or other tools like yo,etc?
Thank you for your time!

2条回答
Anthone
2楼-- · 2019-04-28 20:57

I finally found the solution!

fs.readFile(injectionFile, 'utf8', function (err, injStr) {
injStr = injStr.replace(/svv/g, cname);

fileStream
.pipe(gulpif(rm!=true,injectString.append(injStr),replace(injStr,'')))
.pipe(concat(initialFile))
.pipe(gulp.dest(animation))

...

It took a while, but I AM HAPPY it's over.

Thank you

查看更多
萌系小妹纸
3楼-- · 2019-04-28 21:05

Nice work :) Looks like gulp-replace might be an easier way for folk coming here from google..

var replace = require('gulp-replace');

gulp.task('templates', function(){
  gulp.src(['file.txt'])
    .pipe(replace(/foo(.{3})/g, '$1foo'))
    .pipe(gulp.dest('build/file.txt'));
});
查看更多
登录 后发表回答