For loop in grunt to run the same script but pass in different args - gruntjs

so I have this javascript file that I can currently run with the cmd node runfile.js accountName.
I am trying to make a grunt task that will loop through an array of accountNames to pass into this cmd using grunt-exec.
I am pretty new to grunt and apologize if this is not worded well. Any help is very appreciated!
Current grunt file looks like:
grunt.initConfig({
exec: {
login: function(acct){
return 'node runfile.js' + acct;
}
},
});

I was able to successfully do this with the following code.
module.exports = function(grunt) {
grunt.initConfig({
exec: {
runMobile: {
cmd: function(account, password){
return 'node javascript.js ' + account + ' ' + password
}
},
runDesktop: {
cmd: function(account, password, first_name){
return 'node javascript2.js ' + account + ' ' + password + ' ' + first_name
}
}
}
});
grunt.loadNpmTasks('grunt-exec');
//get our list of accounts
var fs = require('fs');
var data = JSON.parse(fs.readFileSync('node_modules/selenium-webdriver/example/accounts.json', 'utf-8'));
grunt.registerTask('default', 'Running The task',function(){
data.accounts.forEach(function(payload){
grunt.task.run('exec:runMobile:'+payload.account+':'+payload.password);
grunt.task.run('exec:runDesktop:'+payload.account+':'+payload.password+':'+payload.first_name);
});
});
};

Related

[gulp 4]: Trying to run Gulp4 to convert SCSS to CSS

I tried to run the gulp to covert SCSS to CSS,the gulp is working wihout any error but there aren't have any css files output to the target folder, I also tried to change the output path but it still didn't work,and my code is below :
// gulpfile.js
var gulp = require('gulp');
var sass = require('gulp-sass')(require('node-sass'));
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var plumber = require('gulp-plumber');
var browserSync = require('browser-sync').create();
var notify = require('gulp-notify');
var sassLint = require('gulp-sass-lint');
var styleLink = {
sassLink: 'src/**/*.(scss|sass)',
OutputLink: '../css'
}
var browserSyncLink = {
root: '../',
watchHtml: '../*.html',
watchJS: '../*.js'
}
// notify
function showErrorNotify(error) {
var args = Array.prototype.slice.call(arguments);
// Show notification
notify.logLevel(0);
notify
.onError({
title: '[' + error.relativePath + '] Error',
message: '<%= error.messageOriginal %>',
sound: 'Pop'
})
.apply(this, args);
// Keep gulp from hanging on this task
this.emit('end');
}
// sass task
function sassTask() {
return gulp.src(styleLink.sassLink, { sourcemaps: true })
.pipe(sass()) // compile SCSS to CSS
.pipe(autoprefixer())
.pipe(gulp.dest('./', { sourcemaps: '.' }));
}
function browserSyncServer(cb) {
browserSync.init({
server: {
baseDir: browserSyncLink.root
}
})
cb();
}
function browserSyncLoad(cb) {
browserSync.reload();
cb();
}
function sassLinkTask() {
return gulp
.src(styleLink.sassLink)
.pipe(
plumber({
errorHandler: showErrorNotify
})
)
.pipe(sassLint())
.pipe(sassLint.format())
.pipe(sassLint.failOnError());
}
function watchTask() {
gulp.watch('../*.html', browserSyncLoad);
gulp.watch(['src/**/*.+(scss|sass)', '../js/*.js'], gulp.series(gulp.parallel(sassTask, sassLinkTask), browserSyncLoad));
}
exports.default = gulp.series(gulp.parallel(sassTask, sassLinkTask), browserSyncServer, watchTask);
when I ran this code i alos didn't get any error.
It seems no error..
Could anyone please help me ? Thanks.
and please excuse my poor English...
In your watchTask you have this:
src/**/*.+(scss|sass) note the + sign before the alternation.
But in your styleLink variable you have:
var styleLink = {
sassLink: 'src/**/*.(scss|sass)',
OutputLink: '../css'
}
Change to sassLink: 'src/**/*.+(scss|sass)',

SyntaxError: Unexpected token { in Gruntfile.js

I don't manage to configure grunt. I have followed all the steps from Magento2 but I receive this syntax error.
grunt
Loading "Gruntfile.js" tasks...ERROR
>> SyntaxError: Unexpected token {
Warning: Task "default" not found. Use --force to continue.
Aborted due to warnings.
I have reinstalled both the grunt and the node.js, but it doesn't work.
Has anybody had the same problem?
Below you can see the Gruntfile.js ( that is original) posted.
Is it an error of this file or is there another problem?
Gruntfile.js
module.exports = function (grunt) {
'use strict';
var _ = require('underscore'),
path = require('path'),
filesRouter = require('./dev/tools/grunt/tools/files-router'),
configDir = './dev/tools/grunt/configs',
tasks = grunt.file.expand('./dev/tools/grunt/tasks/*'),
themes;
filesRouter.set('themes', 'dev/tools/grunt/configs/themes');
themes = filesRouter.get('themes');
tasks = _.map(tasks, function(task){ return task.replace('.js', '') });
tasks.push('time-grunt');
tasks.forEach(function (task) {
require(task)(grunt);
});
require('load-grunt-config')(grunt, {
configPath: path.join(__dirname, configDir),
init: true,
jitGrunt: {
staticMappings: {
usebanner: 'grunt-banner'
}
}
});
_.each({
/**
* Assembling tasks.
* ToDo: define default tasks.
*/
default: function () {
grunt.log.subhead('I\'m default task and at the moment I\'m empty, sorry :/');
},
/**
* Production preparation task.
*/
prod: function (component) {
var tasks = [
'less',
'autoprefixer',
'cssmin',
'usebanner'
].map(function(task){
return task + ':' + component;
});
if (typeof component === 'undefined') {
grunt.log.subhead('Tip: Please make sure that u specify prod subtask. By default prod task do nothing');
} else {
grunt.task.run(tasks);
}
},
/**
* Refresh themes.
*/
refresh: function () {
var tasks = [
'clean',
'exec:all'
];
_.each(themes, function(theme, name) {
tasks.push('less:' + name);
});
grunt.task.run(tasks);
},
/**
* Documentation
*/
documentation: [
'replace:documentation',
'less:documentation',
'styledocco:documentation',
'usebanner:documentationCss',
'usebanner:documentationLess',
'usebanner:documentationHtml',
'clean:var',
'clean:pub'
],
'legacy-build': [
'mage-minify:legacy'
],
spec: function (theme) {
var runner = require('./dev/tests/js/jasmine/spec_runner');
runner.init(grunt, { theme: theme });
grunt.task.run(runner.getTasks());
}
}, function (task, name) {
grunt.registerTask(name, task);
});
};
Thanks in advance!
I was getting the same error.
I installed node using the following commands and error resolved.
curl -sL https://deb.nodesource.com/setup_8.x | sudo bash -
sudo apt install nodejs
node -v
npm -v
Hope this helps!

the task is getting executed for last value only in grunt custom task

While executing grunt custom task I am iterating a loop, inside the loop I am calling a grunt task while calling I set values using current loop value to the task but when loop execute for alliteration it is setting last value of array always.
var productionUrl = "http://www.abc.de";
var phantomPagesPath = {
"index": "/index.php",
"search": "/Suche?searchString=test",
"warenkorb": "/warenkorb",
"product": "/4-ecksofa",
"cms": "/content/25-service",
"category": "/bestellung",
"pageNotFound": "/404"
};
grunt.initConfig({`phantomas: {
prod: {
options: {
options: {
'timeout': 30
},
buildUi: true
}
}
}`});`
grunt.registerTask('fantomas', 'Custome Phantomas task', function () {
var done = this.async();
var pageUrl = '';
var location = '';
for (var page in phantomPagesPath) {
pageUrl = '';
location = '';
if (phantomPagesPath.hasOwnProperty(page)) {
pageUrl = productionUrl + phantomPagesPath[page];
location = './public/phantomas/' + page + "/";
console.log("process started for: " + pageUrl);
console.log("location: " + location);
grunt.config.set('phantomas.options.url', pageUrl);
grunt.config.set('phantomas.options.indexPath', location);
grunt.task.run('phantomas');
}
}
done();
});
Now Output I am getting
process started for: http://www.abc.de/index.php
location: ./public/phantomas/index/
process started for: http://www.abc.de/Suche?searchString=test
location: ./public/phantomas/search/
process started for: http://www.abc.de/warenkorb
location: ./public/phantomas/warenkorb/
process started for: http://www.abc.de/4-ecksofa
location: ./public/phantomas/product/
process started for: http://www.abc.de/content/25-service
location: ./public/phantomas/cms/
process started for: http://www.abc.de/bestellung
location: ./public/phantomas/category/
process started for: http://www.abc.de/404
location: ./public/phantomas/pageNotFound/
Running "phantomas:prod" (phantomas) task
PHANTOMAS EXECUTION(S) STARTED.
Task are getting executed for all number of entries but the data sent for task is the last entry from loop "pageNotFound",
I mean this process is working 7 times but on each process, it is taking last value of loop.
After searching a lot I came up with the solution that inspite of calling
grunt.task.run('phantomas');
Within the foreach loop, it should be called outside the loop which means the task is going to be executed for one time only. So for this, we need to increase make tasks/target within the task for which I did following code:
grunt.loadNpmTasks('grunt-phantomas');
var phantomPagesPath = {
"index": "/index.php",
"search": "/Suche?searchString=test",
"warenkorb": "/warenkorb",
"product": "/4-ecksofa",
"cms": "/content/25-service",
"category": "/bestellung",
"pageNotFound": "/404"
};
grunt.initConfig({
phantomas: {
//For Executing this task run: grunt fantomas
},
});
// Register customer task for phantomas
grunt.registerTask('fantomas', 'Custome Phantomas task', function () {
var done = this.async();
var pageUrl = '';
var location = '';
for (var page in phantomPagesPath) {
pageUrl = productionUrl + phantomPagesPath[page];
location = './public/phantomas/' + page + "/";
grunt.config.set('phantomas.'+page+'.options.url', pageUrl);
grunt.config.set('phantomas.'+page+'.options.indexPath', location);
grunt.config.set('phantomas.'+page+'.options.buildUi', true);
grunt.config.set('phantomas.'+page+'.options.options.timeout', 30);
var pageUrl = '';
var location = '';
}
grunt.task.run('phantomas');
done();
});
Now run
grunt fantomas

How can I pipe the output from gulp-w3c-css to the console

When I follow the examples for gulp-w3c-css I am unable to get the results to print in the console instead of in an output directory.
Compare how I am using CSSLint and W3C-CSS below. I'd like the function to be identical.
var gulp = require('gulp'),
csslint = require('gulp-csslint'),
cssvalidate = require('gulp-w3c-css');
gulp.task('csslint', () =>
gulp.src('testcss/laxhjalpen.css')
.pipe(csslint('.csslintrc'))
.pipe(csslint.reporter())
);
// Does not work
gulp.task('cssvalid', () =>
gulp.src('testcss/*css')
.pipe(cssvalidate())
// Next line works but is not what I want
.pipe(gulp.dest('reports'))
// I suppose I need to get this construct to work but I can't
.pipe(gutil.buffer(function(err, files) {
if (err) {
gutil.log('An error occured', err);
} else {
// No idea what to write
// files - array of validation results (from manual)
}
}))
);
The very best solution would be just to have a reporter function that works like the csslint.reporter does.
The gulp-w3c-css plugin serializes the validation results for each file to JSON and stores that JSON in the file.contents property. The format of that JSON serialization looks roughly like the following (for more details see the w3c-css documentation):
{
errors: [ { line: 5, message: 'Some error' },
{ line: 42, message: 'Some error' } ],
warnings: [ { line: 13, message: 'Some warning' },
{ line: 23, message: 'Some warning' } ]
}
So all you have to do is parse that JSON and then log the information to the console in any way you want.
Here's a simple example of how you could do it:
var gulp = require('gulp');
var cssvalidate = require('gulp-w3c-css');
var gutil = require('gulp-util');
var map = require('map-stream');
gulp.task('cssvalid', function () {
return gulp.src('testcss/*css')
.pipe(cssvalidate())
.pipe(map(function(file, done) {
if (file.contents.length == 0) {
console.log('Success: ' + file.path);
console.log(gutil.colors.green('No errors or warnings\n'));
} else {
var results = JSON.parse(file.contents.toString());
results.errors.forEach(function(error) {
console.log('Error: ' + file.path + ': line ' + error.line);
console.log(gutil.colors.red(error.message) + '\n');
});
results.warnings.forEach(function(warning) {
console.log('Warning: ' + file.path + ': line ' + warning.line);
console.log(gutil.colors.yellow(warning.message) + '\n');
});
}
done(null, file);
}));
});
I used map-stream instead of gutil.buffer() so that the results for each file are printed as soon as they are available instead of printing everything at the very end.

Execute next grunt.task.run() if previous one failed

I am currently running a set of tasks inside a for loop in grunt. Ex: data.accounts.forEach(function(payload){
grunt.task.run('exec:task1:'+payload.account+':'+payload.password);
grunt.task.run('exec:task2:'+payload.account+':'+payload.password+':'+payload.first_name);
});
Currently the way this is working is if any one of these exec fails then the whole batch fails. I was wondering if there was a way to continue on through the loop even if one of these failed. Like some sort of try/catch.
After thinking about my question for a minute this may be a grunt-exec issue. here is my code for my exec:
exec: {
task1: {
cmd: function(account, password){
return 'node node_module ' + account + ' ' + password
}
},
task2: {
cmd: function(account, password, first_name){
return 'node node_module ' + account + ' ' + password + ' ' + first_name
}
}
The answer to this lies in the grunt-exec
exec: {
task1: {
cmd: function(account, password){
return 'node node_module ' + account + ' ' + password
},
exitCodes: [0,1]
},
task2: {
cmd: function(account, password, first_name){
return 'node node_module ' + account + ' ' + password + ' ' + first_name
},
exitCodes: [0,1]
}

Resources