Using Gulp watch, Axios and Browsersync to do an HTTP get before reloading browser on file change - gulp

I'm trying to watch 2 sets of folders. One set just requires a browser reload on change. The second requires "reinitializing the framework", via a separate, background http get before doing the reload.
My current attempt handles this properly once, but only once. Can you tell me both why and how to fix it? The troublesome portion is in the second watch task.
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'));

Gulp watch passes a "done" callback that must be called in order to proceed. Changing the code to the following solved the problem.
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'));

Related

Electron. content-security-policy is fighting with render.js

I have an electron js application:
const path = require('path');
const url = require('url');
const {app, BrowserWindow, ipcMain, nativeTheme, globalShortcut} = require('electron');
let win;
function createWindow() {
win = new BrowserWindow({
width: 1024,
height: 1024,
icon: path.join(__dirname, "web/img/app.png"),
fullscreen: true,
autoHideMenuBar: true,
webPreferences: {
preload: path.join(__dirname, "web/js/preload.js"),
}
});
win.loadURL(url.format({
pathname: path.join(__dirname, "web/html/index.html"),
protocol: 'file',
slashes: true
}));
win.webContents.openDevTools();
win.on('closed', () => {
win = null;
});
ipcMain.on('sys-shutdown', () => {
app.quit();
});
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
render.js:
window.onload=function() {
console.log("LOAD!");
const sys_shutdown = document.getElementById("SysShutdown");
sys_shutdown.addEventListener('click', async () => {
console.log('hello');
await window.sys.shutdown();
});
}
preload.js:
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('sys', {
shutdown: () => ipcRenderer.send('sys-shutdown')
});
When I start a project, I get an error in the console:
Electron Security Warning (Insecure Content-Security-Policy) This renderer process has either no Content Security
Policy set or a policy with "unsafe-eval" enabled. This exposes users of
this app to unnecessary security risks.
For more information and help, consult
https://electronjs.org/docs/tutorial/security.
This warning will not show up
once the app is packaged.
I tried googling, but the solutions didn't work for me. I tried to allow all rights, but it didn't help either, I don't know what to do anymore...
P.S The console.log("LOAD") line works fine, but the code doesn't work any further.
Please help

Gulp 4 tasks do not run in parallel

I have migrated from gulp 3 to 4. Everything was fine for a week, and then my build pipeline broke. I have a hugo website that should be rebuilt on gulp build.
The build task calls three other tasks in parallel: gulp.parallel("css", "js", "hugo");
When running gulp build, gulp claims it succeeded in 2.19 ms, which is too fast. These three task are supposed to output files to my dist folder, but it does not run my tasks at all.
Running the css, js, and hugo tasks manually in the terminal works as expected.
I am fairly new to gulp 4, so I suspect I am missing some detail. Here is my gulpfile:
import gulp from "gulp";
import cp from "child_process";
import gutil from "gulp-util";
import postcss from "gulp-postcss";
import cssImport from "postcss-import";
import cssnext from "postcss-cssnext";
import BrowserSync from "browser-sync";
import webpack from "webpack";
import webpackConfig from "./webpack.conf";
import cssnano from "cssnano";
import imagemin from "gulp-imagemin";
import imageminMozjpeg from "imagemin-mozjpeg";
import webp from "imagemin-webp";
import gm from "gulp-gm";
const browserSync = BrowserSync.create();
const hugoBin = `./bin/hugo.${process.platform === "win32" ? "exe" : process.platform}`;
const defaultArgs = ["-d", "../dist", "-s", "site"];
if (process.env.DEBUG) {
defaultArgs.unshift("--debug");
}
const hugo = (cb) => {
buildSite(cb);
};
const hugoPreview = (cb) => {
buildSite(cb, gulp.parallel("--buildDrafts", "--buildFuture"));
cb();
};
const build = (cb) => {
gulp.parallel("css", "js", "hugo");
cb();
};
const buildPreview = (cb) => {
gulp.parallel("css", "js", "hugoPreview");
cb();
};
const css = (cb) => {
gulp.src("./src/css/*.css")
.pipe(postcss([
cssImport({
from: "./src/css/main.css"
}),
cssnext(),
cssnano(),
]))
.pipe(gulp.dest("./dist/css"))
.pipe(browserSync.stream());
cb();
};
const js = (cb) => {
const myConfig = Object.assign({}, webpackConfig);
webpack(myConfig, (err, stats) => {
if (err) throw new gutil.PluginError("webpack", err);
gutil.log("[webpack]", stats.toString({
colors: true,
progress: true
}));
browserSync.reload();
cb();
});
};
const webpConvert = (cb) => {
gulp.src("./dist/img/**/*")
.pipe(gm((gmfile) => {
return gmfile.colorspace("rgb");
}))
.pipe(imagemin([
webp({
quality: 75
})
]))
.pipe(gulp.dest("./dist/webp"));
cb();
};
const imgSquash = (cb) => {
return gulp.src("./site/static/img/**/*")
.pipe(imagemin([
imagemin.gifsicle({
interlaced: true,
optimizationLevel: 3
}),
imagemin.jpegtran({
progressive: true
}),
imageminMozjpeg({
quality: 80
}),
imagemin.optipng({
optimizationLevel: 5
}),
imagemin.svgo({
plugins: [{
removeViewBox: true
},
{
cleanupIDs: false
}
]
})
]))
.pipe(gulp.dest("./dist/img"));
};
const server = (cb) => {
browserSync.init({
server: {
baseDir: "./dist"
}
});
gulp.watch("./src/js/**/*.js", js);
gulp.watch("./src/css/**/*.css", css);
gulp.watch("./site/**/*", hugo);
cb();
};
const buildSite = (cb, options) => {
const args = options ? defaultArgs.concat(options) : defaultArgs;
return cp.spawn(hugoBin, args, {
stdio: "inherit"
}).on("close", (code) => {
if (code === 0) {
browserSync.reload("notify:false");
cb();
} else {
browserSync.notify("Hugo build failed :(");
cb("Hugo build failed");
}
});
};
export {
hugo,
hugoPreview,
build,
buildPreview,
css,
js,
webpConvert,
imgSquash,
server
};
When you execute callback in your tasks, gulp thinks that task is finished. Instead of calling callback you should return stream, so that gulp knows when task is finished.
You should change your tasks in something similar like this:
const css = (cb) => {
return gulp.src("./src/css/*.css")
.pipe(postcss([
cssImport({
from: "./src/css/main.css"
}),
cssnext(),
cssnano(),
]))
.pipe(gulp.dest("./dist/css"))
.pipe(browserSync.stream());
// cb(); --comment this line
};
Add 'return' and comment line with cb();

Gulp task not finishing

Being new to gulp. I have the follwing task. I need to spawn a webserver and then another script has to run some stuff against this webserver. I am currently struggling with finishing the script because the browser-sync task does not finish and prevents the script from exit.
'use strict';
const browserSync = require('browser-sync').create();
const cp = require('child_process');
const minimalcss = require('minimalcss');
const gulp = require('gulp');
const clean = require('gulp-clean');
const sourceDir = "_site/";
const deployDir = "public/";
// build the mkdocs Site
gulp.task('build', function() {
return cp.exec('pipenv run mkdocs build --site-dir ' + sourceDir);
});
// Delete _deploy directory first
gulp.task('prepare', function() {
return gulp.src(deployDir, {read: false, allowEmpty: true})
.pipe(clean());
});
// Delete _deploy directory again // just for testing
gulp.task('cleanup', function() {
return gulp.src(deployDir, {read: false, allowEmpty: true})
.pipe(clean());
});
// does not lead to anything, just for testing
gulp.task('inlinecriticalCSS', function(done) {
minimalcss
.minimize({ urls: ['http://localhost:9999/' + 'index.html'] })
.then(result => {
console.log('OUTPUT', result.finalCss.length, result.finalCss);
})
.catch(error => {
console.error(`Failed the minimize CSS: ${error}`);
});
done();
});
// webserver
gulp.task('serve', (done) => {
browserSync.init({
port: 9999,
server: {
baseDir: sourceDir
}
});
done();
});
// default sequence
gulp.task('default', gulp.series(
'prepare',
'build',
'serve',
'inlinecriticalCSS',
'cleanup')
);

Gulp notify not working on successful cucumber steps

I am using gulp-notify to get notification of passing and failing cucumber steps.
The thing is that I only get notifications when it is failing, not when tests are passing.
No errors are thrown but the terminal shows passing tests, and I don't get any notification.
Here the contents of my Gulpfile.js:
var gulp = require('gulp');
var cucumber = require('gulp-cucumber');
var notify = require('gulp-notify');
gulp.task('cucumber', function() {
gulp.src('*features/*')
.pipe(cucumber({
'steps': '*features/step_definitions/*.js',
'support': '*features/support/*.js'
}))
.on('error', notify.onError({
title: 'Red',
message: 'Your test(s) failed'
}))
.pipe(notify({
title: 'Green',
message: 'All tests passed (you can refactor)'
}));
});
gulp.task('watch', function() {
gulp.watch(['features/**/*.feature', 'features/**/*.js', 'script/**/*.js'], ['cucumber']);
});
gulp.task('default', ['watch']);
Any ideas what I could be missing?
I got it working by calling directly cucumberjs, like this:
const gulp = require('gulp');
const notifier = require('node-notifier');
const path = require('path');
gulp.task('cucumber', function() {
const { exec } = require('child_process');
exec('clear && node_modules/.bin/cucumber-js', (error, stdout, stderr) => {
if (error) {
notifier.notify({
title: 'Red',
message: 'Your test(s) failed',
icon: path.join(__dirname, 'failed.png')
});
} else {
notifier.notify({
title: 'Green',
message: 'All tests passed (you can refactor)',
icon: path.join(__dirname, 'passed.png')
});
}
console.log(stdout);
console.log(stderr);
});
});
gulp.task('watch', function() {
gulp.watch(['features/**/*.js', 'script/**/*.js'], ['cucumber']);
});
gulp.task('default', ['cucumber', 'watch']);

Gulp Watch tasks finishing early

I have a gulp file that runs Sass and injects my CSS, app and Bower js files in separate tasks. I would like, at the end of the task, to watch my SCSS files and run Sass on change, and application code and inject new files (with a view to livereload when I can get this working).
Unfortunately, I've run into a problem where my watch tasks end early, therefore no changes are being watched for.
I've read in another question that the watch tasks have to be returned, however, this did not help...
Here is my gulpfile (with prod tasks removed)
const gulp = require('gulp')
// plugins
const concat = require('gulp-concat')
const uglify = require('gulp-uglify')
const rename = require('gulp-rename')
const closure = require('gulp-jsclosure')
const rev = require('gulp-rev')
const sass = require('gulp-sass')
const cssmin = require('gulp-cssmin')
const bower = require('main-bower-files')
const strip = require('gulp-strip-comments')
const inject = require('gulp-inject')
const ngannotate = require('gulp-ng-annotate')
const mainBowerFiles = require('main-bower-files')
const templateCache = require('gulp-angular-templatecache')
const minifyHtml = require('gulp-minify-html')
const path = require('path')
const babel = require('gulp-babel')
const es = require('event-stream')
// configuration variables
const config = {
dir: {
root: 'client/',
app: './Dist/',
vendor: './Dist/',
css: 'client/',
cssMin: './Dist/',
bower: 'client/wwwroot/lib',
index: './Views/Shared/_Layout.cshtml',
indexDir: './Views/Shared',
modules: 'client/app/modules'
},
filters: {
app: 'client/app.js',
appModules: 'client/app/modules/**/*.module.js',
appModuleFiles: 'client/app/modules/**/*.js',
vendors: 'client/vendors/**/*.js',
templates: 'client/app/modules/**/*.html',
client: 'client/app/css/**/*.scss'
}
}
//----------CSS---------
gulp.task('sass', () => {
return gulp.src(['client/app/css/bootstrap.scss', 'client/app/css/app.scss', 'client/app/css/themes/theme-f.scss'])
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('build/css'));
})
gulp.task('inject-css', ['sass'], () => {
var sources = gulp.src(['build/css/bootstrap.css', 'build/css/app.css', 'build/css/theme-f.css'], { read: false }, { name: 'css' });
return gulp.src(config.dir.index)
.pipe(inject(sources))
.pipe(gulp.dest(config.dir.indexDir));
})
//--------End CSS-------
//----------App---------
gulp.task('inject-js', ['inject-bower'], () => {
var sources = gulp.src([config.filters.app, config.filters.appModules, config.filters.appModuleFiles], { read: false });
return gulp.src(config.dir.index)
.pipe(inject(sources))
.pipe(gulp.dest(config.dir.indexDir));
})
//--------End App-------
//---------Vendor-------
gulp.task('inject-bower', ['inject-css'], () => {
let bower = gulp.src(mainBowerFiles(), { read: false }, { relative: true })
return gulp.src(config.dir.index)
// .pipe(inject(es.merge(bower, vendors), { name: 'vendor' }))
.pipe(inject(bower, { name: 'vendor' }))
.pipe(gulp.dest(config.dir.indexDir));
})
//-------End Vendor-----
//----------Prod--------
//---------Watches-------
gulp.task('scripts:watch', () => {
return gulp.watch([config.filters.app, config.filters.appModuleFiles], ['inject-js']);
})
gulp.task('sass:watch', () => {
return gulp.watch(config.filters.scss, ['sass']);
})
gulp.task('watch', ['scripts:watch', 'sass:watch'], () => {
console.log(" ");
console.log("Watching for changes...");
console.log(" ");
})
//-------End Watches-----
//----------Tasks--------
gulp.task('default', ['inject-js', 'inject-bower', 'inject-css',' watch'], () => {
// gulp.watch([config.filters.app, config.filters.appModuleFiles], ['inject-js'])
// gulp.watch(config.filters.scss, ['sass'])
})
As you can probably see from the commented out code, I have also tried running these watched directly inside of the default task.
This is the console output from running gulp
[12:48:12] Using gulpfile C:\source\Icon.Admin\src\UI\Icon.Admin\gulpfile.js
[12:48:12] Starting 'scripts:watch'...
[12:48:12] Finished 'scripts:watch' after 145 ms
[12:48:12] Starting 'sass:watch'...
[12:48:12] Finished 'sass:watch' after 180 μs
[12:48:12] Starting 'watch'...
Watching for changes...
[12:48:12] Finished 'watch' after 159 μs
Any help with this is greatly appreciated!
Fixed this by running my watch tasks inside of the main watch task:
gulp.task('watch', [], () => {
console.log(" ");
console.log("Watching for changes...");
console.log(" ");
gulp.watch([config.filters.app, config.filters.appModuleFiles], ['inject-js']);
gulp.watch(config.filters.client, ['sass']);
})
Well, Inside your sass:watch it refers to config.filters.scss but that is no where to be found in the config object. Probably why your scss isn't compiling.
...
gulp.task('scripts:watch', () => {
return gulp.watch([config.filters.app, config.filters.appModuleFiles], ['inject-js']);
})
gulp.task('sass:watch', () => {
return gulp.watch(config.filters.client, ['inject-sass']);
})
gulp.task('default', ['inject-js', 'inject-bower', 'inject-css', 'scripts:watch', 'sass:watch']);
This should be all you need.