execute a terminal command using node.js - abc

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.

Related

How can I delete a post from a supergroup in telegram with telegram-cli?

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.

Calling Meteor Method from within Particle Photon Stream of Promises produces error: Error("Meteor code must always run within a Fiber. "

I'm connecting to Particle.io event stream and trying to call a Meteor Method with the event name and event data from the stream as arguments.
var Particle = Meteor.npmRequire('particle-api-js');
var particle = new Particle();
var particleLogin = particle.login({
username: Meteor.settings.particle_username,
password: Meteor.settings.particle_password
});
particleLogin.then(
function(data) {
var token = data.body.access_token;
console.log(token);
var eventStream = particle.getEventStream({
deviceId: Meteor.settings.PhotonName,
auth: token
});
eventStream.then(function(stream) {
stream.on('event', function(data) {
console.log(data.name + ": " + data.data);
Meteor.call('newStreamData', data.name, data.data); // Produces aforementioned error
});
});
}
)
I've tried including the call from inside of a Meteor.bindEnvironment block and nothing happens.
stream.on('event', Meteor.bindEnvironment(function(data) {
console.log(data.name + ": " + data.data); // Never gets called
Meteor.call('newStreamData', data.name, data.data); // Never gets called
}));

Xolvio/meteor-cucumber: returning result of this.server.call

I am using the package Xolvio/meteor-cucumber and I'm trying to call a fixture method and use its returned value in a step definition:
Step:
And I fill in the sms code "#smsCodeVerification"
Step definition:
this.Then(/^I fill in the sms code "([^"]*)"$/, function (verificationField, callback) {
var code = this.server.call('getSmsCodeForUser', "+467*******");
console.log("step code: " + code);
this.client
.waitForExist(verificationField, 4000)
.waitForVisible(verificationField, 2000)
.setValue(verificationField, code)
.call(callback);
});
The above code prints:
step code: [object Promise]
The server method looks like this:
'getSmsCodeForUser': function (tel) {
var user = User.findOne({ phone: tel }),
password = Password.findOne({ user: user._id }),
code = parseInt(password.code);
return code;
}
The console log in the step definition will run before the server method is finished, and using the meteors normal way of getting a callback from server methods will not work, it will only return undefined.
this.server.call('getSmsCodeForUser', "+467*******").then(function(resopnse) {
// you can use the response here
});

Run parametrized task using grunt.task.run(taskname)

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);
}
});

How can I do a replace with gridfs-stream?

I'm using this code to do a file update:
app.post("/UploadFile", function(request, response)
{
var file = request.files.UploadedFile;
var name = request.param("Name");
var componentId = request.param("ComponentId");
console.log("Uploading: " + name);
var parameters =
{
filename: name,
metadata:
{
Type: "Screenshot",
ComponentId: componentId
}
};
grid.files.findOne( { "metadata.ComponentId" : componentId }, function(error, existing)
{
console.log("done finding");
if (error)
{
common.HandleError(error);
}
else
{
if (existing)
{
console.log("Exists: " + existing._id);
grid.remove({ _id: existing._id }, function(removeError)
{
if (removeError)
{
common.HandleError(removeError, response);
}
else
{
SaveFile(file, parameters, response);
}
});
}
else
{
console.log("new");
SaveFile(file, parameters, response);
}
}
});
});
function SaveFile(file, parameters, response)
{
console.log("Saving");
var stream = grid.createWriteStream(parameters);
fs.createReadStream(file.path).pipe(stream);
}
Basically I'm checking for a file that has an ID stored in metadata. If it exists, I delete it before my save, and if not I just do the save. It seems to work only sporadically. I sometimes see two erroneous behaviors:
The file will be deleted, but not recreated.
The file will appear to be updated, but it won't actually be replaced until I call my code again. So basically I need to do two file uploads for it to register the replace.
It's very sketchy, and I can't really determine a pattern for if it's going to work or not.
So I'm assuming I'm doing something wrong. What's the right way to replace a file using gridfs-stream?
It's difficult to say for sure from just the code you've provided (i.e. you don't show how the response to the app.post is ultimately handled), but I see several red flags to check:
Your SaveFile function above will return immediately after setting up the pipe between your file and the gridFS store. That is to say, the caller of the code you provide above will likely get control back well before the file has been completely copied to the MongoDB instance if you are moving around large files, and/or if your MongoDB store is over a relatively slow link (e.g. the Internet).
In these cases it is very likely that any immediate check by the caller will occur while your pipe is still running, and therefore before the gridFS store contains the correct copy of the file.
The other issue is you don't do any error checking or handling of the events that may be generated by the streams you've created.
The fix probably involves creating appropriate event handlers on your pipe, along the lines of:
function SaveFile(file, parameters, response)
{
console.log("Saving");
var stream = grid.createWriteStream(parameters);
pipe = fs.createReadStream(file.path).pipe(stream);
pipe.on('error', function (err) {
console.error('The write of " + file.path + " to gridFS FAILED: ' + err);
// Handle the response to the caller, notifying of the failure
});
pipe.on('finish', function () {
console.log('The write of " + file.path + " to gridFS is complete.');
// Handle the response to the caller, notifying of success
});
}
The function handling the 'finish' event will not be called until the transfer is complete, so that is the appropriate place to respond to the app.post request. If nothing else, you should get useful information from the error event to help in diagnosing this further.

Resources