首页 > 解决方案 > 使用 Gulp watch、Axios 和 Browsersync 在文件更改时重新加载浏览器之前进行 HTTP 获取

问题描述

我正在尝试观看 2 组文件夹。一组只需要在更改时重新加载浏览器。第二个需要在重新加载之前通过单独的后台http get“重新初始化框架”。

我目前的尝试正确处理了一次,但只有一次。你能告诉我为什么以及如何解决它吗?麻烦的部分是在第二个监视任务中。

const gulp = require('gulp');
const axios = require("axios");
const bs = require('browser-sync').create(); 
const { reload } = bs;

const url = "http://127.0.0.1:80/healthcheck?fwreinit=1";

var paths = {
        refresh: [
            "./layouts/**/*.*",
            "./views/**/*.*",
            "./includes/**/*.js",
            "./includes/**/*.css"
        ],
        reinit: [
            "./handlers/**/*.*",
            "./models/**/*.*",
            "./interceptors/**/*.*",
            "./config/**/*.*"
        ]
    }

gulp.task('watch', () => {
    gulp.watch(paths.refresh, (done) => {
        reload();
        done();
    });
    gulp.watch(paths.reinit, () => {
        console.log("Reinitializing framework");
        axios.get(url)
        .then(response => {
            console.log(response.data.trim());
            reload();
        })
        .catch(error => {
            console.log("Error:  Please ensure you have a /healthcheck route set up in /config/router.cfc!");
            console.log("Error:  Once you've done that, please shut down commandbox then try browsersync again.");
        });
    });
});

gulp.task('proxy', () => {
    bs.init({
        proxy: "localhost:80",
        port: 81,
        open: true,
        notify: false
    });
});

gulp.task('default', gulp.parallel('watch', 'proxy'));

标签: gulpaxiosgulp-watch

解决方案


Gulp watch 传递一个“完成”回调,必须调用它才能继续。将代码更改为以下解决了该问题。

const gulp = require('gulp');
const axios = require("axios");
const bs = require('browser-sync').create(); 
const { reload } = bs;

const url = "http://127.0.0.1:80/healthcheck?fwreinit=1";

var paths = {
        refresh: [
            "./layouts/**/*.*",
            "./views/**/*.*",
            "./includes/**/*.js",
            "./includes/**/*.css"
        ],
        reinit: [
            "./handlers/**/*.*",
            "./models/**/*.*",
            "./interceptors/**/*.*",
            "./config/**/*.*"
        ]
    }

gulp.task('watch', () => {
    gulp.watch(paths.refresh, (done) => {
        reload();
        done();
    });
    gulp.watch(paths.reinit, (done) => {
        console.log("Reinitializing framework");
        axios.get(url)
        .then(response => {
            console.log(response.data.trim());
            reload();
            done();
        })
        .catch(error => {
            console.log("Error:  Please ensure you have a /healthcheck route set up in /config/router.cfc!");
            console.log("Error:  Once you've done that, please shut down commandbox then try browsersync again.");
        });
    });
});

gulp.task('proxy', () => {
    bs.init({
        proxy: "localhost:80",
        port: 81,
        open: true,
        notify: false
    });
});

gulp.task('default', gulp.parallel('watch', 'proxy'));

推荐阅读