user791793
user791793

Reputation: 701

How to load contents of an external file into gulp browser-sync

I am loading browser-sync proxy and want to load search and replace terms from an external file in order to amend the page as it is loaded into a browser.

The reason I want to load the search and replace terms from a separate file is because I want to make use of gulp-watch and reload browser-sync as the search and replace terms are updated.

My Project folder:

Contents of gulpfile.js:

var gulp = require('gulp'),
fs = require("fs"),
browserSync = require('browser-sync');

var proj_url = "http://www.example.com";
var search_text = "";
var replace_text = "";

gulp.task('readRegEx', function() {
    return gulp.src('regex/*.txt')
    .pipe(fs.readFile("regex/search.txt", "utf-8", function(err, data) {
        search_text = data;
    }))
    .pipe(fs.readFile("regex/replace.txt", "utf-8", function(err, data) {
        replace_text = data;
    }))
});

gulp.task('browser-sync', function() {
    browserSync({
        proxy: {
            target: proj_url
        },
        rewriteRules: [
            {
                match: search_text,
                fn: function (match) {
                    return replace_text;
                }
            }
        ]
    });
});

gulp.task('default', ['readRegEx','browser-sync'], function() {
    gulp.watch(['regex/*.txt'], [browserSync.reload]);
});

This doesn't work. I get the following error:

TypeError: Cannot call method 'on' of undefined ...

Upvotes: 0

Views: 566

Answers (1)

Benja
Benja

Reputation: 4154

For that to work you need to make browser-sync dependant in readRegEx

gulp.task('browser-sync', ['readRegEx'], function() {

this guarantees the proper execution order.

then you can make readRegEx sync (and simpler) this way:

gulp.task('readRegEx', function() {
    search_text = fs.readFileSync("regex/search.txt", "utf-8").toString();
    replace_text = fs.readFileSync("regex/replace.txt", "utf-8").toString();
});

Upvotes: 2

Related Questions