I did stackoverflow search and looked at Grunt API docs but couldn't find a way to run a parametrized task using grunt.task.run(taskname).
I have a simple task which accepts a parameter and prints the message on console:
grunt.registerTask('hello', 'greeting task', function(name) {
if(!name || !name.length)
grunt.warn('you need to provide a name');
console.log('hello ' + name + '!');
});
I call the above task using below task which validates the task and if task exists then it runs it:
grunt.registerTask('validateandruntask', 'if task available then run given task', function(taskname) {
if(!taskname || !taskname.length) {
grunt.warn('task name is needed to run this task');
}
if(!grunt.task.exists(taskname)) {
grunt.log.writeln('this task does not exist!');
} else {
grunt.log.writeln(taskname + ' exists. Going to run this task');
grunt.task.run(taskname);
}
});
Now from command line, I am passing 'hello' task as parameter to 'validateandruntask' but I am not been able to pass the parameter to 'hello' task from command line:
This is what I tried on command line but it didn't work:
grunt validateandruntask:hello=foo
grunt validateandruntask:hello:param=name
First thing, the way to pass an arg through the command line is to use :.
For example to call hello directly:
grunt hello:you
To call it with multiple arguments, just separate them by :, like
grunt hello:mister:president
And to use these multiple arguments in the task, you do the same as plain Javascript: use arguments (all details here):
grunt.registerTask('hello', 'greeting task', function(name) {
if(!name || !name.length)
grunt.warn('you need to provide a name');
// unfortunately arguments is not an array,
// we need to convert it to use array methods like join()
var args = Array.prototype.slice.call(arguments);
var greet = 'hello ' + args.join(' ') + '!';
console.log(greet);
});
Then you want to call grunt validateandruntask:hello:mister:president, and modify your code to handle the variable parameters as well:
grunt.registerTask('validateandruntask', 'if task available then run given task', function(taskname) {
if(!taskname || !taskname.length) {
grunt.fail.fatal('task name is needed to run this task');
}
var taskToCall = taskname;
for(var i = 1; i < arguments.length; i++) {
taskToCall += ':' + arguments[i];
}
console.log(taskToCall);
if(!grunt.task.exists(taskname)) {
grunt.log.writeln('this task does not exist!');
} else {
grunt.log.writeln(taskname + ' exists. Going to run this task');
grunt.task.run(taskToCall);
}
});
Related
we have a group in telegram and we have a rule says no one must leave a message in group between 23 to 7 am , I wanna delete messages comes to group between these times automatically . could anyone tell me how I can do that with telegram cli or any other telegram client?
Use new version of telegram-cli. It's not fully open source, but you can download a binary from its site. Also you can find some examples there.
I hope the following snippet in JavaScript will help you to achieve your goal.
var spawn = require('child_process').spawn;
var readline = require('readline');
// delay between restarts of the client in case of failure
const RESTARTING_DELAY = 1000;
// the main object for a process of telegram-cli
var tg;
function launchTelegram() {
tg = spawn('./telegram-cli', ['--json', '-DCR'],
{ stdio: ['ipc', 'pipe', process.stderr] });
readline.createInterface({ input: tg.stdout }).on('line', function(data) {
try {
var obj = JSON.parse(data);
} catch (err) {
if (err.name == 'SyntaxError') {
// sometimes client sends not only json, plain text process is not
// necessary, just output for easy debugging
console.log(data.toString());
} else {
throw err;
}
}
if (obj) {
processUpdate(obj);
}
});
tg.on('close', function(code) {
// sometimes telegram-cli fails due to bugs, then try to restart it
// skipping problematic messages
setTimeout(function(tg) {
tg.kill(); // the program terminates by sending double SIGINT
tg.kill();
tg.on('close', launchTelegram); // start again for updates
// as soon as it is finished
}, RESTARTING_DELAY, spawn('./telegram-cli', { stdio: 'inherit' }));
});
}
function processUpdate(upd) {
var currentHour = Date.now().getHours();
if (23 <= currentHour && currentHour < 7 &&
upd.ID='UpdateNewMessage' && upd.message_.can_be_deleted_) {
// if the message meets certain criteria, send a command to telegram-cli to
// delete it
tg.send({
'ID': 'DeleteMessages',
'chat_id_': upd.message_.chat_id_,
'message_ids_': [ upd.message_.id_ ]
});
}
}
launchTelegram(); // just launch these gizmos
We activate JSON mode passing --json key. telegram-cli appends underscore to all fields in objects. See all available methods in full schema.
Iam trying to execute a terminal command using node.js spawn
for that am using the code
console.log(args)
var child = spawn("hark", args, {cwd: workDir});
child.stdout.on('data', function(data) {
console.log(data.toString())
});
child.stderr.on('data', function(data) {
console.log('stdout: ' + data);
});
child.on('close', function(code) {
console.log('closing code: ' + code);
});
But it treated greater than>as string">" and
getting output as
tshark: Invalid capture filter "> g.xml"
That string isn't a valid capture filter (syntax error).
See the User's Guide for a description of the capture filter syntax.
How can i use > without string
You can use file streams to put all output from spawned hark to g.xml.
Example:
// don't need ">" in args
var args = [' 02:00:00:00' ,'-s','pdml'],
logStream = fs.createWriteStream('./xml');
var spawn = require('child_process').spawn,
child = spawn('tshark', args);
child.stdout.pipe(logStream);
child.stderr.pipe(logStream);
child.on('close', function (code) {
console.log('child process exited with code ' + code);
});
Because of child here is a stream, you can just pipe it into your logged file stream.
I want to run a command but after a task finishes in grunt.
uglify: {
compile: {
options: {...},
files: {...}
}
?onFinish?: {
cmd: 'echo done!',
// or even just a console.log
run: function(){
console.log('done!');
}
}
},
Either run a command in shell, or even just be able to console.log. Is this possible?
Grunt does not support before and after callbacks, but next version could implement events that would work in the same way, as discussed in issue #542.
For now, you should go the task composition way, this is, create tasks for those before and after actions, and group them with a new name:
grunt.registerTask('newuglify', ['before:uglify', 'uglify', 'after:uglify']);
Then remember to run newuglify instead of uglify.
Another option is not to group them but remember to add the before and after tasks individually to a queue containing uglify:
grunt.registerTask('default', ['randomtask1', 'before:uglify', 'uglify', 'after:uglify', 'randomtask2']);
For running commands you can use plugins like grunt-exec or grunt-shell.
If you only want to print something, try grunt.log.
The grunt has one of the horrible code that I've ever seen. I don't know why it is popular. I would never use it even as a joke. This is not related to "legacy code" problem. It is defected by design from the beginning.
var old_runTaskFn = grunt.task.runTaskFn;
grunt.task.runTaskFn = function(context, fn, done, asyncDone) {
var callback;
var promise = new Promise(function(resolve, reject) {
callback = function (err, success) {
if (success) {
resolve();
} else {
reject(err);
}
return done.apply(this, arguments);
};
});
something.trigger("new task", context.name, context.nameArgs, promise);
return old_runTaskFn.call(this, context, fn, callback, asyncDone);
}
You can use callback + function instead of promise + trigger. This function will request the new callback wrapper for new task.
I have javascript:
$('#link').on('click', function ()
{
console.log('Click link');
});
And i write dalekjs-test:
module.exports = {
'Clicked link': function (test)
{
test.open('http://localhost/')
.click('#link')
.done();
}
};
And after running $ dalek tests/test.js i wanna see that Click link.
How can i get it?
This is currently not possible & I do not know if it will be possible in the future.
The thing is, you have to overwrite the console object in the browser. That would mean, you have to actively change something in the environment of your user. And I don't think that this is a good idea.
Although, there might be a workaround for your Problem ;)
Lets say, you write a debugging function (as a client side javascript file) like this:
window.myDebugLog = [];
window.myDebug = function () {
var list = Array.prototype.slice.call(arguments, 0);
window.myDebugLog.push(list);
}
Now, lets modify your logging function a bit:
$('#link').on('click', function () {
var msg = 'Click link';
console.log(msg);
window.myDebug(msg);
});
With this you can access & output your logging. Even better, with some ClojureCompiler or Esprima fun, you could parse out that debugging stuff when building your production code, so that you do not need to ship it.
In your Dalek test, just do this:
module.exports = {
'Clicked link': function (test) {
test.open('http://localhost/')
.click('#link')
.execute(function () {
this.data('logs', window.myDebugLog);
})
.log.message(function () {
return JSON.stringify(test.data('logs').pop());
})
.done();
}
};
That will give you your log stuff in the Command Line Output.
If you´re not willing to add this extra function call, you could also overwrite the console.log on your own. But that could cause some trouble, so take this with a grain of salt:
window.myDebugLog = [];
window.oldLog = console.log;
console.log = function () {
var list = Array.prototype.slice.call(arguments, 0);
window.myDebugLog.push(list);
window.oldLog.apply(console, list);
};
Hope that helps you with your problem.
Is there a way to pass an argument from a alias task like this into on of the calling tasks:
grunt.registerTask('taskA', ['taskB', 'taskC'])
grunt taskA:test
so that task taskB and taskC will be called with the parameter test?
You can create a dynamic alias task like this:
grunt.registerTask('taskA', function(target) {
var tasks = ['taskB', 'taskC'];
if (target == null) {
grunt.warn('taskA target must be specified, like taskA:001.');
}
grunt.task.run.apply(grunt.task, tasks.map(function(task) {
return task + ':' + target;
}));
});
Here is the FAQ with another example in the Grunt docs: http://gruntjs.com/frequently-asked-questions#dynamic-alias-tasks