Nodemon syncronous task execution before restarting - node.js

I'm running gulp as build tool for my nodejs server. I have one issue with nodemon (Nodemon is a utility that will monitor for any changes in your source and automatically restart your server. ), since i'm not able to execute a gulp task to transform my ecmascript 6 code before the server restarts.
This is my code. Nodemon documentation says that syncronous task execution is possible with node version 0.12.0. My node version is 0.12.6. Anyone noticed the same problem or knows how to fix?
https://github.com/JacksonGariety/gulp-nodemon
var gulp = require('gulp');
var noDemon = require('nodemon');
var babel = require('gulp-babel');
var plumber = require('gulp-plumber');
gulp.task('server', ['transformES6'], function () {
noDemon({
script : 'server/dist/server.js',
ext : 'js',
env : {
PORT : 8000
},
ignore : [
'./node_modules/**',
'./server/dist/**'
],
tasks : ['transformES6']
}).on('restart', function () {
var now = new Date();
console.log('server is restarting: ' + now.getHours() + ' Hours, ' + now.getMinutes() + ' Minutes, ' + now.getSeconds() + ' Seconds');
});
});
gulp.task('transformES6', function () {
return gulp.src(['./server/**/**/**/**/*.js', '!./server/dist/'])
.pipe(plumber())
.pipe(babel())
.pipe(gulp.dest('./server/dist/'));
})
Thanks in advance!
Greetings Mauro

Related

gulp-watch runs all tasks if it watches html files

There is a task 'serve' with watch functions as shown below:
gulp.task('serve', function() {
gulp.watch(['source/scripts/*.js'], ['concatjs', reload]);
gulp.watch(['source/styles/*.css'], ['concatcss', reload]);
gulp.watch(['app/static/*.html'], [reload]);
});
When I update js or css files gulp executes only concatjs or concatcss tasks correspondingly. But if to update the html file gulp executes all tasks even the tasks that wasn't registered to the watch function and it throws an error:
[18:26:31] Starting 'lesstocss'...
[18:26:31] Starting 'concatjs'...
[18:26:31] Starting 'concatcss'...
[18:26:31] Starting 'serve'...
[error] You tried to start Browsersync twice! To create multiple instances, use browserSync.create().init()
[18:26:31] Finished 'serve' after 6.1 ms
[18:26:31] Finished 'lesstocss' after 38 ms
[18:26:31] Finished 'concatjs' after 47 ms
[18:26:31] Finished 'concatcss' after 41 ms
Maybe gulp works with the html files in another way? All code I use:
var gulp = require('gulp');
var concat = require('gulp-concat');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var less = require('gulp-less');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('lesstocss', function () {
return gulp.src('source/styles/*.less')
.pipe(sourcemaps.init())
.pipe(less())
.pipe(sourcemaps.write())
.pipe(gulp.dest('source/styles/'));
});
gulp.task('concatjs', function() {
return gulp.src(['source/scripts/mls.js', 'source/scripts/main.js'])
.pipe(concat('result.js'))
.pipe(gulp.dest('app/static/scripts/'));
});
gulp.task('concatcss', function() {
return gulp.src(['source/styles/mls.css', 'source/styles/main.css'])
.pipe(concat('result.css'))
.pipe(gulp.dest('app/static/styles/'));
})
gulp.task('serve', function() {
browserSync.init({
proxy: "localhost:3000",
browser: "google chrome",
notify: false,
open: 'local'
});
gulp.watch(['source/scripts/*.js'], ['concatjs', reload]);
gulp.watch(['source/styles/*.css'], ['concatcss', reload]);
gulp.watch(['app/static/*.html'], [reload]);
});
var gulp = require("gulp");
var changedInPlace = require("gulp-changed-in-place");
var browserSync = require("browser-sync").create();
var sass = require("gulp-sass");
var uglify = require("gulp-uglify");
var concat = require("gulp-concat");
var rename = require("gulp-rename");
var autoprefixer = require("gulp-autoprefixer");
var cleanCSS = require("gulp-clean-css");
// var sourcemaps = require("gulp-sourcemaps");
// var runSequence = require("run-sequence");
// Static Server + watching scss/html files
gulp.task("browsersync", ["sass"], function() {
browserSync.init({
server: {
baseDir: "./",
index: "home.html"
},
ghostMode: false
});
gulp.watch("./scss/*.scss", ["sass"]);
gulp.watch("./*.html").on("change", browserSync.reload);
gulp.watch("./js/*.js").on("change", browserSync.reload);
});
// Compile sass into CSS & auto-inject into browsers
gulp.task("sass", function() {
return gulp.src("./scss/*.scss")
.pipe(changedInPlace())
.pipe(sass().on("error", sass.logError))
.pipe(gulp.dest("./css"))
.pipe(browserSync.stream());
});
At this point I thought it would be instructive to show my working gulpfile.js. It uses sass but you can swap that. Note it uses the preferred
var browserSync = require("browser-sync").create();
and avoids the unusual and possibly problematic arrays you have in your watch statements. But if you really have 2 'serve' tasks defined that is probably your problem (see my comment below)
I am not sure the following line is valid syntax:
gulp.watch(['app/static/*.html'], [reload]);
gulp.watch(glob[, opts], tasks) : when used this way - as you are doing - tasks is an array of STRINGS which themselves are created by gulp.task(). See the docs
Names of task(s) to run when a file changes, added with gulp.task()
from https://github.com/gulpjs/gulp/blob/master/docs/API.md#gulpwatchglob--opts-tasks-or-gulpwatchglob--opts-cb
We definitely need to see reload and the rest of your gulpfile.js
Here is sample code which works with browserSync reload for example:
gulp.watch("./scss/*.scss", ["scss-watch"]);
gulp.watch("./*.html").on("change", browserSync.reload);
// gulp.watch("./css/*.css").on("change", browserSync.reload);
gulp.watch("./js/*.js").on("change", browserSync.reload);

Gulp/ Node - Errors on SASS Compile

I currently am using Gulp to run various tasks, which includes compiling and minifying SASS (I am also utilizing Gulp Watch). I am having the issue where when I make changes to a file (specifically app.scss), It spits out a rather uninformative error:
"C:\Program Files (x86)\JetBrains\PhpStorm 2016.1\bin\runnerw.exe" "C:\Program Files\nodejs\node.exe" C:\Users\Matthew\PhpstormProjects\mattrick\node_modules\gulp\bin\gulp.js --color --gulpfile c:\Users\Matthew\PhpstormProjects\website\gulpfile.js watch
[20:48:35] Using gulpfile c:\Users\Matthew\PhpstormProjects\website\gulpfile.js
[20:48:35] Starting 'watch'...
[20:48:35] Finished 'watch' after 7.94 ms
events.js:85
throw er; // Unhandled 'error' event
^
Error: ENOENT, stat 'c:\Users\Matthew\PhpstormProjects\website\resources\assets\sass\app.scss___jb_tmp___'
at Error (native)
Process finished with exit code 1
I'm really not sure what is causing this error, and from Googling, it appears to happen in many different circumstances. I'm not too sure what I am doing wrong. My gulpfile is below:
var gulp = require('gulp');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var cleanCSS = require('gulp-clean-css');
var plumber = require('gulp-plumber');
var del = require('del');
var config = {
bowerDir: './bower_components/',
publicDir: './public',
};
//Build Tasks
gulp.task('build', ['clean'], function() {
gulp.start(['css', 'fonts', 'js']);
});
//Clean Dir
gulp.task('clean', function() {
return del([config.publicDir + "/css", config.publicDir + "/fonts", config.publicDir + "/js"]);
});
//CSS Concat + Minification
gulp.task('css', function() {
return gulp.src(
[
config.bowerDir + 'bootstrap-sass/assets/stylesheets',
config.bowerDir + 'fontawesome/scss',
'./resources/assets/sass/app.scss'
])
.pipe(plumber())
.pipe(sass({
errLogToConsole: true
}))
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(gulp.dest(config.publicDir + '/css'));
});
//Font Awesome
gulp.task('fonts', function() {
return gulp.src(config.bowerDir + '/fontawesome/fonts/**.*')
.pipe(plumber())
.pipe(gulp.dest(config.publicDir + '/fonts'));
});
//JavaScript Concat + Uglify
gulp.task('js', function() {
return gulp.src(
[
config.bowerDir + '/jquery/dist/jquery.min.js',
config.bowerDir + '/bootstrap-sass/assets/javascripts/bootstrap.min.js'
])
.pipe(plumber())
.pipe(concat('app.js'))
.pipe(uglify())
.pipe(gulp.dest(config.publicDir + "/js"));
});
//Watch Task
gulp.task('watch', function() {
watch(['./resources/assets/sass/*', config.bowerDir + '/bootstrap-sass/assets/stylesheets/**'], batch(function(events, done) {
gulp.start('build', done);
}));
});
//Default Task
gulp.task('default', ['build']);
I would really appreciate any help you could provide. Thank you!
The __jb_tmp__ suffix signifies a temp file created by JetBrains applications like PhpStorm. When saving a file the file contents are first written to a temp file which is then renamed. By the time gulp.watch() tries to stat() the temp file it's already gone.
Try limiting your gulp.watch() glob from:
watch(['./resources/assets/sass/*',
to only SASS/SCSS files:
watch(['./resources/assets/sass/*.{sass,scss}',

Gulp stream error on Uglify

I am writing a gulp script for the first time and I am having hard time being able to uglify my JS files based on gulp-if, I actually do think my code is correct :
var gulp = require('gulp');
var gutil = require('gulp-util');
var gulpif = require('gulp-if');
var concat = require('gulp-concat');
var del = require('del');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var minifyCSS = require('gulp-minify-css');
var watch = require("gulp-watch");
var argv = require('yargs').argv;
var paths = {
styles: ['css/maaap.css'],
stylesUfe: ['css/ufe.css'],
scripts: ['js/lang.js', 'js/bootstrap.js', 'js/jquery.js', 'js/leaflet.js', 'js/emm.js', 'js/markercluster.js', 'js/moment.js', 'js/geolocate.js'],
scriptsUfe: ['js/ufe.js', 'js/exif.js', 'js/binaryajax.js', 'js/canvasResize.js']
};
// Not all tasks need to use streams
// A gulpfile is just another node program and you can use all packages available on npm
gulp.task('clean', function(cb) {
console.log(cb);
del(['build'], cb);
});
// Merge all the css files from paths.styles then move it to build/css/style.css
// If you append --ufe you also merge the files from paths.stylesUfe
// If you append --prod your file become build/css/style.min.css and is compressed
gulp.task('styles', ['clean'], function() {
var source = (!argv.ufe) ? paths.styles : paths.styles.concat(paths.stylesUfe);
return gulp.src(source)
.pipe(concat('style.min.css'))
.pipe(gulpif(argv.prod, minifyCSS()))
.pipe(gulp.dest('build/css'));
});
// Merge all the css js files from paths.scripts then move it to build/js/livemap.js
// If you append --ufe you also merge the files from paths.scriptsUfe
// If you append --prof your file become build/js/livemap.min.js and is compressed
gulp.task('scripts', function() {
var source = (!argv.ufe) ? paths.scripts : paths.scripts.concat(paths.scriptsUfe);
return gulp.src(source)
.pipe(concat('livemap.min.js'))
.pipe(gulpif(argv.prod, uglify()))
.pipe(gulp.dest('build/js'))
});
gulp.task('watch', function() {
watch({glob: 'js/**/*.js'}, function (files) {
gulp.start('scripts'); // run the compile task
});
watch({glob: 'css/*.css'}, function (files) {
gulp.start('styles'); // run the compile task
});
});
// The default task (called when you run `gulp` from cli)
gulp.task('default', ['scripts', 'styles']);
The error logs I got in my console are very strange to me :
stream.js:94
throw er; // Unhandled stream error in pipe.
^
Error
at new JS_Parse_Error (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:189:18)
at js_error (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:197:11)
at croak (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:656:9)
at token_error (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:664:9)
at unexpected (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:670:9)
at expr_atom (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1154:13)
at maybe_unary (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1327:19)
at expr_op (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1349:33)
at expr_ops (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1362:16)
at maybe_conditional (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1367:20)
at maybe_assign (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1391:20)
at expression (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1410:20)
at expr_list (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1177:24)
Any ideas ?

nodeJS Agenda library - start jobs on server start

im using agenda library (https://github.com/rschmukler/agenda/)
I can create and run jobs correctly, but i need to start jobs when i start the server.
I do it this in a module:
var startAlerts = function(){
log.debug('alerts', 'launching alerts');
console.log('alerts', 'launching alerts');
var agenda = new require('agenda')({
db: {
address: db.serverConfig.name + "/" + db.databaseName,
collection: 'alerts'
},
processEvery: '24 hours',
maxConcurrency: 250
});
agenda.start();
};
startAlerts();
But the jobs dont start..What im doing wrong?
Thanks.

How can you get grunt to run automatically each day?

I'd like to run my protractor end-to-end tests automatically each day.
Currently I can do
$ grunt
In the test directory and they run.
Is there a way to get them to run automatically each day at a specific time?
I've tried using cron, but according to this, I'd have to make all of my require paths into absolute paths, which I don't want to do.
Use a node script and setInterval:
var exec = require('child_process').exec
var path = require('path')
var running = false
var run = function(what, where) {
if (running === true) return
running = true
// by default, just run grunt
what = what || 'grunt'
// by default, run on grunt in the current working directory
where = path.resolve(where || path.join(process.cwd(), 'Gruntfile.coffee'))
what += ' --gruntfile=' + where
exec(what, { cwd: path.dirname(where) }, function(err, stdout, stderr) {
if (err || stderr) { /* log the error somewhere */ }
/* log the stdout if needed*/
console.log(stdout)
running = false
})
}
setInterval(function() {
run(/* set what to run, where to run */)
/* or even multiple gruntfiles and node projects */
}, 24 * 60 * 60 * 1000) // once a day
This is platform agnostic, easy to start and stop, easy to maintain and customize.
Check out a library like https://www.npmjs.org/package/forever for running a node script forever. Or many of the other ways: nohup, monit, upstart, etc.
Using Kyle Robinson Young's answer along with the node module cron, I came up with the following which runs the gruntfile every day at 5:00pm:
var cronJob = require('cron').CronJob
, exec = require('child_process').exec
, path = require('path')
, running = false
;
var run = function(what, where) {
if (running === true) {
return;
}
running = true;
// by default, just run grunt
what = what || 'grunt';
// by default, run on grunt in the current working directory
where = path.resolve(where || path.join(process.cwd(), 'Gruntfile.js'));
what += ' --gruntfile=' + where;
exec(what, { cwd: path.dirname(where) }, function(err, stdout, stderr) {
if (err || stderr) {
console.log(err);
}
/* log the stdout if needed*/
console.log(stdout);
running = false;
});
};
new cronJob('00 00 17 * * *', function(){
console.log('Running Gruntfile ' + new Date());
var what = 'grunt'
, where
;
run(what, where);
}, null, true);

Resources