Search code examples
javascriptsearchreplacegulpmatch

How to search a string from a file and replace it to another with Gulp


I'd like to use Gulp to get a selector from a file test1.js and replace it to test2.js

test1.js

@Component({
    selector: 'app-root',
    ...
})
export class AppComponent {}

So, I want to get "app-root" from test1.js

test2.js

var selector = "#selector"
function() {}

In the test2.js, i want replace "#selector" by "app-root".

I know how to replace a string by another string in a file:

gulp.src('test2.js', {base: 'src/'})
.pipe(replace(new RegExp(/#selector/, 'g'), (match, p1) => {
    return 'app-root';
}))
.pipe(gulp.dest('dist'));

But i don't know how to pass "app-root" to the stream replace.

How could i do that with Gulp ?

Thanks !


Solution

  • I found how to do that with map-stream

    var gulp = require('gulp');
    var map = require('map-stream');
    var fs = require('fs');
    
    gulp.task('default', function() {
        gulp.src('./test1.js')
            .pipe(map(function(file, callback) {
                var test = file.contents.toString().match(/selector: '(.*)'/i);
                fs.readFile('./test2.js', function read(err, data) {
                    if (test) {
                        fs.writeFile('./test2.js', data.toString().replace('#selector', test[1]));
                    }
                });
            }));
    });