Show output in Grunt as command runs? - javascript

Here I get no output and the command runs forever:
grunt.registerTask('serve', function () {
var done = this.async();
grunt.util.spawn({
cmd: 'jekyll',
args: ['serve'],
stdio: 'inherit'
}, function (err, res, exit_code) {
res.stdout && console.info(res.stdout);
exit_code && console.error(res.stderr);
done(err);
});
});
I want output (and the command to run until error or interrupt).

Thanks for the answers, #Lihau-Tan was close to the right one.
Combining that answer with my attempt and I came up with this solution:
grunt.registerTask('serve', function () {
var child = grunt.util.spawn({
cmd: 'jekyll',
args: ['serve', '-P', process.env.PORT || 4001],
stdio: 'inherit'
}, this.async());
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
});

Try this:
grunt.registerTask('serve', function(){
var done = this.async();
var child = grunt.util.spawn({
cmd: 'jekyll',
args: ['serve']
}, function(){
...
});
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
});
See: Grunt spawned process not capturing output

You can use grunt log
Following functions available
grunt.log.write(msg)
grunt.log.writeln([msg])
grunt.log.error([msg])
grunt.log.errorlns(msg)
grunt.log.ok([msg])
grunt.log.oklns(msg)
grunt.log.subhead(msg)
grunt.log.writeflags(obj, prefix)
grunt.log.debug(msg)

Related

Issue bundling javascript with gulp js

I'm bundling my javascript files using the task runner gulp js, during the development of an application I'm noticing a certain issue.
When I add the new feature(reveal a password) script refuses to work because of the form modal script which can be seen below.
'use strict';
var modal__button = document.getElementById("enquiry-form-trigger");
var close__button = document.getElementById("close");
modal__button.addEventListener("click", function (){
var modal = document.getElementById("modal-form");
modal.classList.add("fadeIn");
modal.style.visibility = "visible";
});
close__button.addEventListener("click", function (){
var modal = document.getElementById("modal-form");
modal.classList.remove("fadeIn");
modal.style.visibility = "hidden";
});
When the above script and this other script below
"use strict"
document.getElementById("password-reveal-modal").addEventListener("click", function (){
var x = document.getElementById("password-modal");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
});
The password reveal feature doesn't work, but when I paste it in chrome's dev tools works perfectly.
I'm not sure why it wont work without pasting it into the dev tools, it's baffling me, I'm not sure if its my setup or if its the custom javascript.
This is my gulp file setup in case anyone wants to check it, I don't see an issue but Ive only been using gulp for about 3 or 4 months.
var gulp = require("gulp"),
sass = require("gulp-sass"),
image = require("gulp-image"),
concat = require("gulp-concat"),
browserSync = require('browser-sync').create(),
reload = browserSync.reload,
minifyEjs = require("gulp-minify-ejs"),
stripEJSComments = require('gulp-strip-comments'),
nodemon = require('gulp-nodemon'),
plumber = require("gulp-plumber"),
ejs = require("ejs"),
uglify = require("gulp-uglify");
//Build task
gulp.task("build", ["ejs", "styles", "images", "javascript", "routes", "models", "middleware"], function () {
console.log("Build Success");
});
//start up sequence tasks
gulp.task('init', ["nodemon"], function () {
browserSync.init({
proxy: 'http://localhost:2000', //Index.js port number
port: 2128, // The port browser sync runs on
serveStatic: [ './public/', "./assets/"], // What files browser sync should have access to
reloadOnRestart: true, // Enable auto reload
ghostMode:false, //Stops session mirroring
open: "external", //Opens up on an external address (xxx.xxx.x.xx:3128)
});
});
//Starts the express server
gulp.task('nodemon', function (done) {
var running = false; //Default State
return nodemon({
script: 'index.js', //Index file for the JS project
watch: ["./assets/", "./public/"] //What nodemon has access to
})
.on('start', function () {
if (!running) {
done();
}
running = true;
})
//Minor Delay Of 500ms Upon Restart
.on('restart', function () {
setTimeout(function () {
reload();
}, 500);
});
});
//SCSS Task
gulp.task("styles", function () {
gulp.src("./assets/stylesheet/APP.scss")
.pipe(plumber())
.pipe(sass({
outputStyle: 'compressed'
}))
.pipe(gulp.dest("./public/stylesheet/"))
.pipe(browserSync.stream({ stream: true }));
});
//Compiles the express route/s
gulp.task("routes", function () {
gulp.src([
"./assets/routes/*.js"
])
.pipe(plumber())
.pipe(gulp.dest("./public/routes/"))
.pipe(browserSync.stream({ stream: true }));
});
//Compiles the express route/s
gulp.task("models", function () {
gulp.src("./assets/models/*.js")
.pipe(plumber())
.pipe(gulp.dest("./public/models/"))
.pipe(browserSync.stream({ stream: true }));
});
//Image minification
gulp.task("images", function () {
return gulp.src("./assets/images/*")
.pipe(image())
.pipe(gulp.dest("./public/images"))
.pipe(browserSync.stream({ stream: true }));
});
//Client javascript
gulp.task("javascript", function () {
gulp.src([
"./node_modules/jquery/dist/jquery.js",
"./node_modules/tether/dist/js/tether.js",
"./node_modules/bootstrap/dist/js/bootstrap.js",
"./assets/scripts/**/**/*.js"
])
.pipe(plumber())
.pipe(concat("main.js"))
.pipe(gulp.dest("./public/scripts/"))
.pipe(browserSync.stream({ stream: true }));
});
//Middleware task
gulp.task("middleware", function () {
gulp.src("./assets/middleware/*.js")
.pipe(plumber())
.pipe(concat("index.js"))
.pipe(gulp.dest("./public/middleware/"))
.pipe(browserSync.stream({ stream: true }));
});
//EJS task
gulp.task("ejs", function () {
gulp.src("./assets/views/**/*.ejs")
.pipe(plumber())
.pipe(stripEJSComments())
.pipe(minifyEjs({}))
.pipe(gulp.dest("./public/views"))
.pipe(browserSync.stream({ stream: true }));
});
//Default task array
gulp.task("default", ["init", "build"], function (done) {
gulp.watch("./assets/stylesheet/**/*.scss", ["styles"]);
gulp.watch("./assets/scripts/*", ["javascript"]);
gulp.watch("./assets/routes/*.js", ["routes"]);
gulp.watch("./assets/models/*.js",["models"]);
gulp.watch("./assets/images/*",["images"]);
gulp.watch("./assets/views/**/*.ejs",["ejs"]);
browserSync.reload();
done();
});
The two files which are causing the issue are the only files as I have tested each files and its only these two files weirdly so something is causing it to clash.
If you want me to upload my project to github just let me know and I will upload the latest version to my update branch.
I have exhausted all my knowledge into this problem and I am completely stuck now.
If anyone could help a fellow developer out it would be greatly appreciated.
cheers,
alex
I needed to ensure the DOM had fully loaded before the script could be executed.

Can Some give an elaborate example of using Custom Jasmine Reporter for protractor. I am unable to understand Tutorial

Can Some give an elaborate example of using Custom Jasmine Reporter . I would like someone to help me with a sample test with two assertions . how to add the reporter in protractor conf.js and how it can help me . No where in the internet there is a example apart from just the reference .
check the one I use:
First check if all the necessary dependencies are installed (check the begin of the code)
Then copy+paste this to you Conf.js:
//In my case I installed the dependencies locally thats why comes from lib folder
var jasmineReporters = require('./lib/node_modules/jasmine-reporters');
var HTMLReport = require('./lib/node_modules/protractor-html-reporter-2');
var fs = require('./lib/node_modules/fs-extra');
onPrepare: function () {
fs.emptyDir('./Execution_Results/reports/xml/', function (err) {
if (err != ""){
console.log(err);
}
});
fs.emptyDir('./Execution_Results/reports/results/screenshots', function (err) {
if (err != ""){
console.log(err);
}
});
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: './Execution_Results/reports/xml/',
filePrefix: 'xmlresults'
}));
jasmine.getEnv().addReporter({
specDone: function (result) {
//if (result.status == 'failed') {
browser.getCapabilities().then(function (caps)
{
var browserName = caps.get('browserName');
browser.takeScreenshot().then(function (png) {
var stream = fs.createWriteStream('./Execution_Results/reports/results/screenshots/' + browserName + '-' + result.fullName + '.png');
stream.write(new Buffer(png, 'base64'));
stream.end();
});
});
//}
}
});
},
//HTMLReport called once tests are finished
onComplete: function() {
var browserName, browserVersion;
var capsPromise = browser.getCapabilities();
capsPromise.then(function (caps) {
browserName = caps.get('browserName');
browserVersion = caps.get('version');
platform = caps.get('platform');
testConfig = {
reportTitle: 'Protractor Test Execution Report',
outputPath: './',
outputFilename: 'Execution_Results/reports/results/IV2_Test_Results',
screenshotPath: './screenshots/',
testBrowser: browserName,
browserVersion: browserVersion,
modifiedSuiteName: false,
screenshotsOnlyOnFailure: true,
testPlatform: platform
};
new HTMLReport().from('./Execution_Results/reports/xml/xmlresults.xml', testConfig);
});
},
jasmineNodeOpts: {
showColors: true, // Use colors in the command line report.
// If true, display spec names.
isVerbose: true,
},
the folders will be created automatically inside the folder where your conf.js is located so after the execution just access the 'Execution_Results/reports' and open the html report
OnPrepare will generate the xml file with all the results
OnComplete will transform the xml into html report
I'm using this reporter, Just follow the steps from this link to set the conf.js https://www.npmjs.com/package/protractor-jasmine2-screenshot-reporter

Grunt task containing multiple spawn tasks will only run the first task

I have the following three tasks set up which use grunt.util.spawn to handle various Git tasks:
grunt.registerTask('git-add', function() {
grunt.util.spawn({
cmd : 'git',
args: ['add', '.'],
});
});
grunt.registerTask('git-commit', function(message) {
grunt.util.spawn({
cmd : 'git',
args: ['commit', '-m', message],
});
});
grunt.registerTask('git-push', function(origin, branch) {
grunt.util.spawn({
cmd : 'git',
args: ['push', origin, branch],
});
});
Running each of these individually works as aspected, so by running:
$ grunt git-add
$ grunt git-commit:"commit message"
$ grunt git-push:origin:"branch name"
I can successfully commit and push my changes. So how come when combining these 3 tasks into their own task like so, only the first task (git-add) gets run?
var target = grunt.option('target');
grunt.registerTask('push-feature', [
'git-add',
'git-commit:' + target,
'git-push:origin:feature/' + target
]);
I should be able to run $ grunt push-feature --target=12345, assuming my branch is called 12345, to have all those 3 tasks run, but only the first git-add task runs. If I remove the git-add task, the next one (git-commit) is the only task which executes.
What am I missing to just be able to have these 3 tasks run in sequence?
This might be due to async trouble.
Try to mark your tasks as async when declaring them, and use the callback option for spawn. Here's an example with your first task:
grunt.registerTask('git-add', function () {
var done = this.async(); // Set the task as async.
grunt.util.spawn({
cmd: 'git',
args: ['add', '.'] // See comment below about this line
}, done); // Add done as the second argument here.
});
Also note you have an additional comma, that may be interfering with operation:
args: ['add', '.'], // <- this comma should be dropped.

yeoman sub-generator testing with composeWith

I have a generator-generator app with its own local sub-generator app. The situation is that I want the sub-generator to invoke atleast once with pre-defined argument when I run the main 'app' generator. Everything works fine except the npm test fails.
Main 'app' generator: yo mygen.
Sub generator: yo mygen:foo "lorem ipsum".
Here is the test.js
/*global describe, beforeEach, it*/
'use strict';
var path = require('path'),
yg = require('yeoman-generator');
var helpers = require('yeoman-generator').test;
var assert = require('yeoman-assert');
describe(' running `yo mygen`', function () {
before(function (done) {
var deps = [
[helpers.createDummyGenerator(), 'mygen:foo', 'blah blah blah']
];
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(__dirname, './temp')) // Clear the directory and set it as the CWD
.withOptions({ mongoose: 'app', 'skip-install': true }) // Mock options passed in
.withPrompts({
'dbName': 'demo',
'useUserAuth': false
})
.withGenerators(deps)
.on('end', done);
//done();
});
it('can be imported without blowing up', function () {
var app = require('../app');
assert(app !== undefined);
});
it('creates all required MVC files', function (done) {
var expected = [
// add files you expect to exist here.
'package.json',
'app.js',
'bower.json',
'routes/index.js',
'public/css/style.css',
'public/js/script.js',
'views/index.html',
'README.md',
'.editorconfig',
'.jshintrc'
];
assert.file(expected);
done();
});
});
describe('í ¼ running `yo mygen:foo`', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../schema'))
.inDir(path.join(__dirname, './temp')) // Clear the directory and set it as the CWD
.withOptions({ mongoose: 'schema' }) // Mock options passed in
.withArguments(['ha ha ha ha hha'])
.on('end', done);
//done();
});
describe('foo generator', function () {
it('foo can be imported without blowing up', function () {
var app = require('../foo');
assert(app !== undefined);
});
it('created new MVC files for foo', function (done) {
var expected = [
// add files you expect to exist here.
'view/t1.js',
'models/t1.js',
'controller/t1.js'
];
assert.file(expected);
done();
})
});
});
And in app/index.js, in order to invoke the sub-generator, i have used:
mygenGenerator.prototype.install = function install(){
this.installDependencies();
this.composeWith("mygen:foo", {args: ["humpty dumpty saton a wall"]});
};
Searched all possible answers on stackoverflow and everywhere else. Can't figure out what to do.
Test Cases for npm test fails:
Remove the composeWith line from index.js and the test passes.
keep the composeWith line, the test goes to infinity, eventually exceed 2000ms quota and failing.

Gruntfile getting error codes from programs serially

I want to create a grunt file that runs 3 grunt tasks serially one after another regardless of whether they fail or pass. If one of the grunts task fails, I want to return the last error code.
I tried:
grunt.task.run('task1', 'task2', 'task3');
with the --force option when running.
The problem with this is that when --force is specified it returns errorcode 0 regardless of errors.
Thanks
Use grunt.util.spawn: http://gruntjs.com/api/grunt.util#grunt.util.spawn
grunt.registerTask('serial', function() {
var done = this.async();
var tasks = {'task1': 0, 'task2': 0, 'task3': 0};
grunt.util.async.forEachSeries(Object.keys(tasks), function(task, next) {
grunt.util.spawn({
grunt: true, // use grunt to spawn
args: [task], // spawn this task
opts: { stdio: 'inherit' }, // print to the same stdout
}, function(err, result, code) {
tasks[task] = code;
next();
});
}, function() {
// Do something with tasks now that each
// contains their respective error code
done();
});
});

Categories

Resources