Gulp error: events.js:72 - npm

I've been trying out (or trying to get working) a jekyll style guide from: https://github.com/davidhund/jekyll-styleguide#user-content-requirements
My gulpfile is:
var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var minifycss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var clean = require('gulp-clean');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
// Handy file paths
paths = {
scss: "./static/scss/",
css: "./static/css/",
img: "./static/img/",
js: "./static/js/"
}
// SASS
gulp.task('sass', function() {
// Be specific in what file to process
return gulp.src(paths.scss+'app.scss')
.pipe(sass({ style: 'expanded' }))
.pipe(autoprefixer('> 5%', 'last 2 version', 'ie 9'))
.pipe(minifycss())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest(paths.css))
// .pipe(gulp.dest('./_site/static/css/'))
// .pipe(notify({ message: 'Styles task complete' }));
});
// COPY CSS
gulp.task('copycss', function() {
return gulp.src(paths.css+'app.min.css')
.pipe(gulp.dest('./_site/static/css/'))
// .pipe(notify({ message: 'Copied Minified CSS to _site/static/css' }));
});
// JEKYLL
// Start a `jekyll build` task
// From: http://stackoverflow.com/questions/21293999/use-jekyll-with-gulp
gulp.task('jekyll-build', function() {
require('child_process').spawn('jekyll', ['build', '--config=_config.dev.yml'], {stdio: 'inherit'});
});
// Start a `jekyll build --watch` task
gulp.task('jekyll-watch', function() {
require('child_process').spawn('jekyll', ['build', '--watch', '--config=_config.dev.yml'], {stdio: 'inherit'});
});
// BROWSER-SYNC
gulp.task('browser-sync', function() {
// reload when Jekyll-generated files change
browserSync.init(['./_site/static/**/*.css', './_site/**/*.html'], {
server: {
baseDir: './_site/'
}
});
});
// WATCH
gulp.task('watch', function() {
// TEST: [Only] Run `jekyll build` when I update (the version in) settings.yml
// gulp.watch('./_config.yml', ['jekyll']);
// Run Sass when I update SCSS files
gulp.watch(paths.scss+'**/*.scss', ['sass', 'copycss']);
// gulp.watch(paths.js+'**/*.js', ['scripts']);
// gulp.watch(paths.img+'**/*', ['images']);
});
// DEFAULT task
gulp.task('default', ['jekyll-watch', 'watch','browser-sync']);
Whenever I run gulp I just get:
events.js:72
throw er; // Unhandled 'error' event
^
Error: spawn ENOENT
at errnoException (child_process.js:998:11)
at Process.ChildProcess._handle.onexit (child_process.js:789:34)

The problem you are facing is that you are not handling error, so, when gulp finds an error, it throw it, but "nobody" is taking care of it, which causes gulp to break.
In order to keep executing gulp, you have to define your error handlers and do whatever you want to do with error, typically, print on the cli what is going on.
You also need to identify which part of your code is "throwing" the error, in your case, its caused by the "watchers": a watcher listen for additional events or to add files to the watch. So, a watcher is throwing the error.
You have to catch it !
Add an on handler event after the execution of plugins, and pass this error to a function that will pint it (or something else), but will not break "the watch" (John Snow will be proud) and allows you to identify the error, fix it, at keep watching without restarting gulp manually.
PS: Don't forgot to define "the catcher function" !
Your code could be something like this:
var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var minifycss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var clean = require('gulp-clean');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
// Handy file paths
paths = {
scss: "./static/scss/",
css: "./static/css/",
img: "./static/img/",
js: "./static/js/"
}
// SASS
gulp.task('sass', function() {
// Be specific in what file to process
return gulp.src(paths.scss+'app.scss')
.pipe(sass({ style: 'expanded' })).on('error', errorHandler)
.pipe(autoprefixer('> 5%', 'last 2 version', 'ie 9'))
.pipe(minifycss())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest(paths.css))
// .pipe(gulp.dest('./_site/static/css/'))
// .pipe(notify({ message: 'Styles task complete' }));
});
// COPY CSS
gulp.task('copycss', function() {
return gulp.src(paths.css+'app.min.css')
.pipe(gulp.dest('./_site/static/css/'))
// .pipe(notify({ message: 'Copied Minified CSS to _site/static/css' }));
});
// JEKYLL
// Start a `jekyll build` task
// From: http://stackoverflow.com/questions/21293999/use-jekyll-with-gulp
gulp.task('jekyll-build', function() {
require('child_process').spawn('jekyll', ['build', '--config=_config.dev.yml'], {stdio: 'inherit'});
});
// Start a `jekyll build --watch` task
gulp.task('jekyll-watch', function() {
require('child_process').spawn('jekyll', ['build', '--watch', '--config=_config.dev.yml'], {stdio: 'inherit'});
});
// BROWSER-SYNC
gulp.task('browser-sync', function() {
// reload when Jekyll-generated files change
browserSync.init(['./_site/static/**/*.css', './_site/**/*.html'], {
server: {
baseDir: './_site/'
}
});
});
// WATCH
gulp.task('watch', function() {
// TEST: [Only] Run `jekyll build` when I update (the version in) settings.yml
// gulp.watch('./_config.yml', ['jekyll']);
// Run Sass when I update SCSS files
gulp.watch(paths.scss+'**/*.scss', ['sass', 'copycss']);
// gulp.watch(paths.js+'**/*.js', ['scripts']);
// gulp.watch(paths.img+'**/*', ['images']);
});
// DEFAULT task
gulp.task('default', ['jekyll-watch', 'watch','browser-sync']);
// Handle the error
function errorHandler (error) {
console.log(error.toString());
this.emit('end');
}
Note the error handler definition at the end and the addition of .on('error', errorHandler) on your sass task.

Related

Gulpfile.js error: Did you forget to signal async completion

I just recently made a gulfile.js by helping google, but I face a problem which says
The following tasks did not complete: default, serve, sass
Did you forget to signal async completion?
Here is my gulpfile.js:
var gulp = require("gulp");
var browserSync = require("browser-sync").create();
var sass = require("gulp-sass");
// Compile sass into CSS & auto-inject into browsers
gulp.task("sass", function () {
return gulp
.src("ruby/assets/scss/*.scss")
.pipe(sass())
.pipe(gulp.dest("ruby/assets/css"))
.pipe(browserSync.stream());
});
// Static Server + watching scss/html files
gulp.task(
"serve",
gulp.series("sass", function () {
browserSync.init({
server: "./ruby/",
});
gulp.watch("ruby/assets/scss/*.scss", gulp.series("sass"));
gulp.watch("ruby/*.html").on("change", browserSync.reload);
})
);
gulp.task("default", gulp.series("serve"));
Here is my boilerplate:
I have no idea what the error is.

Transition from gulp to npm

I am trying to move away from gulp and use npm scripts. We have developers that use different versions of node/gulp and the dependence on plugins and deprecation's has been an unwanted hassle.
I am trying to convert our gulp script to npm but there are a few areas I'm stuck on. I'm having issues converting from gulp-sourcemaps to npm map-stream and converting from gulp-uglify to uglifyjs.
Here is the gulp file we are currently using:
/*
This file in the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var pump = require('pump');
var del = require('del');
// set a variable telling us if we're building in release
var isRelease = true;
if (process.env.NODE_ENV && process.env.NODE_ENV !== 'Release') {
isRelease = false;
}
var config = {
//Include all js files but exclude any min.js files
src: ['Scripts/*.js', '!Scripts/*.min.js']
}
//delete the output file(s)
gulp.task('clean', function () {
//del is an async function and not a gulp plugin (just standard nodejs)
//It returns a promise, so make sure you return that from this task function
// so gulp knows when the delete is complete
return del(['Scripts/*.min.js', 'Scripts/Maps/*.map']);
});
// Combine and minify all files from the app folder
// This tasks depends on the clean task which means gulp will ensure that the
// Clean task is completed before running the scripts task.
gulp.task('scripts', ['clean'], function (cb) {
pump([
gulp.src(config.src),
sourcemaps.init(),
uglify({ mangle: isRelease }),
rename({ suffix: '.min' }),
sourcemaps.write('Maps', { includeContent: false, sourceRoot: './' }),
gulp.dest('Scripts/')
],
cb
);
});
//Set a default tasks
gulp.task('default', ['scripts'], function () { });
Here is my current npm script (still has some errors):
/*
This is the main entry point for defiinng npm tasks
*/
const del = require('del');
var map = require('map-stream');
var pump = require('pump');
var vfs = require('vinyl-fs');
var uglifyjs = require('uglify-js');
// set a variable telling us if we're building in release
var isRelease = true;
if (process.env.NODE_ENV && process.env.NODE_ENV !== 'Release') {
isRelease = false;
}
console.log(process.env.NODE_ENV);
//task to delete output files
(async () => {
const deletedPaths = await del(['Scripts/*.min.js', 'Scripts/Maps/*.map']);
console.log('Deleted files and folders:\n', deletedPaths.join('\n'));
})();
var log = function(file, cb) {
console.log(file.path);
cb(null, file);
};
// vinyl metadata object
// Include all js files but exclude any min.js files
pump([
vfs.src(['Scripts/*.js', '!Scripts/*.min.js']),
map(log),
uglifyjs({mangle:isRelease}),
rename({ suffix: '.min' }),
(vfs.dest('Scripts/'))
])
The mapping should create a Maps folder under the Scripts directory.
Scripts
--Maps
--jquery.min.js.map
--jquery-1.4.1.min.js.map
Any help would be appreciated.
Thanks!
/*
* This is the main entry point for defining npm tasks
* Author: *****
* Date: 06/03/2019
*/
const del = require('del');
var Uglify = require("uglify-js"),
fs = require('fs'),
async = require('async'),
path = require('path'),
rename = require('rename'),
parentDir = 'Scripts';
Checking the build type (Release, Production, Debug etc.) is done using node so there weren't any changes to be made in this part of the script.
// set a variable telling us if we're building in release
var isRelease = true;
if (process.env.NODE_ENV && process.env.NODE_ENV !== 'release') {
isRelease = false;
}
console.log(process.env.NODE_ENV);
As for the npm del module, I opted for the synchronous method. The reason is that I wanted each file to be processed separately instead of in parallel. The async method kept missing the .acingore file and there aren't many files that need to be deleted anyway.
// Returns an array of deleted paths
const deletedPaths = del.sync(['Scripts/*.min.js', 'Scripts/Maps/*.map', 'Scripts/.acignore']);
console.log('Deleted files and folders:\n', deletedPaths.join('\n'));
This block does all the work. This function runs an array of functions in series, each passing their results to the next in the array. Each function is passed a callback on completion.
async.waterfall([
function (cb) {
fs.readdir(parentDir, cb);
},
function (files, cb) {
// files is just an array of file names, not full path
console.log('Files being looped through:\n');
// run 10 files in parallel
async.eachLimit(files, 10, function (filename, done) {
var filePath = path.join(parentDir, filename);
var sourceFile = filename;
if (!fs.lstatSync(filePath).isDirectory()) {
// create a .temp file to be minified
fs.copyFileSync(filePath, filePath + '.temp', (err) => {
if (err) throw err;
// console.log(filePath + ' was copied to ' + filePath + '.temp');
});
// path the .temp file
var tempfilePath = path.join(parentDir, filename + '.temp');
// console.log('tempfilePath: ' + tempfilePath);
// check for /Maps directory, if not, create it
var mapsDir = parentDir + '/Maps';
try {
if (!fs.existsSync(mapsDir)) {
fs.mkdirSync(mapsDir)
}
} catch (err) {
console.error(err)
}
// rename file to add .min suffix for minified files
filename = rename(filename, { suffix: '.min' });
// console.log('filename after rename\n' + filename + '\n');
var newfilePath = path.join(parentDir, filename);
// console.log('filePath after rename\n' + newfilePath + '\n');
// Synchronous rename
fs.renameSync(tempfilePath, newfilePath);
// get contents of sourceFile
// The source file must be interpolated with [] in order
// to be mapped correctly, otherwise your map will get the content
// of the source file but not have a link back to the source
try {
var code = {
[sourceFile]: fs.readFileSync(filePath, 'utf-8')
};
console.log(code);
} catch (e) {
console.log('Error:', e.stack);
}
// minify file
// the syntax for uglifyjs minify is minify(code, options)
// therefore you need the contents of the file in order to minify it
// and source map it
var uglyCode = Uglify.minify(code,
{
mangle: isRelease,
sourceMap: {
includeSources: false,
filename: '../' + filename,
root: '../',
url: 'Maps/' + filename,
},
}
);
// console.log('Source file: ' + sourceFile);
// write minified file to directory
fs.writeFile(newfilePath, uglyCode.code, function (err) {
if (err) {
console.log(err);
} else {
console.log(filename + " has been mangled");
}
}
);
// write map file to directory
fs.writeFile(mapsDir + '/' + filename + '.map', uglyCode.map, function (err) {
if (err) {
console.log(err);
} else {
console.log(filename + '.map' + " has been mapped");
}
}
);
done();
}
}, cb);
}
], function (err) {
err && console.trace(err);
console.log('\nNo more files in path\n');
});
SIDE NOTE: If you're running node 10+ and you cannot set the path to npm in your .csproj file, install node globally and you don't need to set the path.
Hopefully my comments in the code are sufficient. Good luck if you are trying to move away from gulp and transition to npm!

Browser-Sync - changes to .scss not appearing in browser but appearing in .css

I am trying to set up a project with browser-sync in Gulp 4. When executing my default task "gulp"- browser-sync does load and launches an instance of chrome at local:3000 and all changes made in my "src" folder to .html files reload as expected after saving. However, anything in my "sass" folder as ".scss" is compiled correctly and moved to my "dist" folder as a ".css" after saving, however, any changes are not reloaded into my browser upon saving.
I have tried re-arranging the position of browserSync.reload so that it takes place before any minimizing but that did not solve the issue. I have tried looking at the browsersync + Gulp.js doc but to no avail. I am still new with Gulp 4 and learning so it is very possible I have just mucked up something in the code or am trying to execute a series of commands that do not work together well.
/* REQUIRED PACKAGES EDITED */
var gulp = require('gulp');
watch = require('gulp-watch');
browserSync = require('browser-sync').create();
concat = require('gulp-concat');
sass = require('gulp-sass');
uglify = require('gulp-uglify');
imagemin = require('gulp-imagemin');
pump = require('pump');
cleanCSS = require('gulp-clean-css');
/* GULP TASKS */
/* Pipe .HTML to Dist Folder */
gulp.task('html', function(cb) {
pump([
gulp.src('src/*.html'),
gulp.dest('dist'),
browserSync.stream()
],
cb
);
});
/* Clean and Pipe .SCSS to Dist Folder */
gulp.task('sass', function(cb) {
pump([
gulp.src('src/sass/*.scss'),
sass().on('error', sass.logError),
cleanCSS(),
gulp.dest('dist/css'),
browserSync.stream()
],
cb
);
});
gulp.task('sass:watch', function(){
gulp.watch('src/sass/*.scss', ['sass']);
});
/* Concat, Uglify & Pipe .JS to Dist Folder */
gulp.task('js', function(cb) {
pump([
gulp.src('src/js/*.js'),
concat('main.js'),
uglify(),
gulp.dest('dist/js'),
browserSync.stream()
],
cb
);
});
/* Minify & Pipe .IMG to Dist Folder */
gulp.task('imagemin', function(cb) {
pump([
gulp.src('src/img/*'),
imagemin(),
gulp.dest('dist/img'),
browserSync.stream()
],
cb
);
});
/* Browser-Sync */
gulp.task('browser-sync', function() {
browserSync.init({
server: {
baseDir: './src'
}
});
});
gulp.task('watch', function() {
gulp.watch('./src/sass/*.scss', gulp.series('sass'));
gulp.watch('./src//js/*.js', gulp.series('js'));
gulp.watch('./src/*.html', gulp.series('html'));
});
/* RUN DEFAULT - RUN ALL TASKS */
gulp.task('default', gulp.parallel('html', 'sass', 'js', 'imagemin', 'browser-sync', 'watch'));
I would expect everything to function but again, upon any changes made to the .scss file, they take place and are saved to the .css file but the changes do not appear in the browser. Any help is very much appreciated!
Change this:
gulp.watch('./src/sass/*.scss', gulp.series('sass'), browserSync.reload);
to:
gulp.watch('./src/sass/*.scss', gulp.series('sass', browserSync.reload));
Also in this:
gulp.task('sass', function(cb) {
pump([
gulp.src('src/sass/*.scss'),
// don't call browserSync.stream() before sass()
// plus you already have it in your scss watch to reload
// so either move this to the end - after gulp.dest - and remove it from the watch
// or remove it from here and leave in the watch
// browserSync.stream(),
sass().on('error', sass.logError),
cleanCSS(),
gulp.dest('dist/css')
],
cb;
);
});
// in your watch task:
gulp.watch("./src/*.html", { events: 'all' }, function(cb) {
browserSync.reload();
cb();
});
gulp.task('html', function(cb) {
pump([
gulp.src('src/*.html'),
gulp.dest('dist'),
// browserSync.stream()
],
cb
);
});

Browser-sync TypeError args.cb is not a function

I'm using browser-sync in gulp task for example :
gulp.task('gulp-task',function(){
browserSync.init({
server:{
baseDir: 'app'
}
})
//rest of task
});
I use this gulp task in gulp watch for( for example ) app/**/*.html like :
gulp.task('watch',function(){
gulp.watch('app/**/*.html', ['gulp-task']);
});
for first time change in html files everything is ok but for next changes i get error:
TypeError: args.cbn is not a function ...
guys said to install latest version for browser-sync with command below :
npm install browser-sync#latest --save-dev
and it doesn't helped.
I'm getting the same error. what's wrong?
I also ran into this issue and solved it by removing the brackets from the callback in the watch task.
Try changing your watch task to:
gulp.task('watch',function(){
gulp.watch(['app/**/*.html'], 'gulp-task');
});
Or better yet, try using the reload method with something like this:
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var jshint = require('gulp-jshint');
var watch = require('gulp-watch');
var reload = browserSync.reload;
gulp.task('default', ['jshint', 'serve', 'watch']);
gulp.task('jshint', function() {
return gulp.src('src/app/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
// Static server
gulp.task('serve', function() {
browserSync.init({
server: {
baseDir: "./src"
}
});
});
gulp.task('watch', function() {
gulp.watch(['src/**/*.html', 'src/app/**/*.js'], reload);
});
After reading the document of browser-sync,I noticed that the method .init( config, cb ) has two parameters.So,change your code to this:
gulp.task('gulp-task',function(){
browserSync.init({
server:{
baseDir: 'app'
}
})
//rest of task
},function(){
// something you want to do
});
While defining the 'watch' we need to declare what all tasks need to be run before watch, this will sort the problem out.
Extra parameter with pre-planned tasks needs to be added in the watch task list of parameters.
gulp.task('watch', ['browserSync', 'sass'], function(){...})
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
gulp.task('hello', function() {
console.log('Hello Gulp-Shash');
});
gulp.task('sass', function(){
return gulp.src('app/scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('app/css'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: 'app'
},
})
})
gulp.task('watch', ['browserSync', 'sass'], function(){
gulp.watch('app/scss/**/*.scss', ['sass']);
})

Debugging protractor test in intellij idea

I have project and I use protractor test. But I would like use debugging but I don't know how to create config for him.
It is my protractor.conf.js
'use strict';
var paths = require('./.yo-rc.json')['generator-gulp-angular'].props.paths;
exports.config = {
capabilities: {
'browserName': 'chrome'
},
specs: [paths.e2e + '/**/*.js'],
mochaOpts: {
timeout: 5000
},
framework: 'mocha'
};
And e2e-tests.js gulp file:
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserSync = require('browser-sync');
module.exports = function(options) {
gulp.task('webdriver-update', $.protractor.webdriver_update);
gulp.task('webdriver-standalone', $.protractor.webdriver_standalone);
function runProtractor (done) {
gulp.src(options.e2e + '/**/**.js')
.pipe($.protractor.protractor({
configFile: 'protractor.conf.js'
}))
.on('error', function (err) {
// Make sure failed tests cause gulp to exit non-zero
throw err;
})
.on('end', function () {
// Close browser sync server
browserSync.exit();
done();
});
}
gulp.task('protractor', ['protractor:src']);
gulp.task('protractor:src', ['serve:e2e', 'webdriver-update'], runProtractor);
gulp.task('protractor:dist', ['serve:e2e-dist', 'webdriver-update'], runProtractor);
};
Help me please fix this issue because write code without quick watch and other good components not very well.