Not able to call PowerShell from NodeJS - node.js

I have this PowerShell that I usually call like this :
powershell -ExecutionPolicy Bypass -File "D:\tmp\getmember2.ps1" -groupnames "ABC"
Now, I need to call this from my nodejs. So, this is what I create :
var spawn = Meteor.npmRequire("child_process").spawn;
child = spawn("powershell.exe",["-ExecutionPolicy ByPass -File d:\\tmp\\getmember2.ps1 -groupnames \"ABC\""]);
child.stdout.on("data",function(data){
console.log("Powershell Data: " + data);
});
child.stderr.on("data",function(data){
console.log("Powershell Errors: " + data);
});
child.on("exit",function(){
console.log("Powershell Script finished");
});
child.stdin.end();
However I am getting this error :
I20170222-16:58:25.257(8)? API started
I20170222-16:58:26.175(8)? Powershell Errors: At line:1 char:2
I20170222-16:58:26.174(8)?
I20170222-16:58:26.175(8)? + CategoryInfo : ParserError: (-:String)
[], ParentContainsErrorR
I20170222-16:58:26.175(8)? + - <<<< ExecutionPolicy ByPass -File d:\tmp\getmember2.ps1
I20170222-16:58:26.176(8)? Powershell Errors: ecordException
I20170222-16:58:26.176(8)? Powershell Errors: + FullyQualifiedErrorId : MissingExpressionAfterOperator
I20170222-16:58:26.176(8)? Powershell Errors:
I20170222-16:58:26.177(8)?
I20170222-16:58:26.174(8)? Powershell Errors: Missing expression after unary operator '-'.
I20170222-16:58:26.259(8)? Powershell Script finished
Any idea on why it is not working?

Change my code to use child_process.exec() instead of spawn().
As described in this link :
Spawn is best used to when you want the child process to return a large amount of data to Node - image processing, reading binary data etc. Use exec to run programs that return result statuses, instead of data.
Code changed to below and run my powershell neatly.
var child = exec('Powershell.exe -executionpolicy ByPass -File d:\\tmp\\getmember.ps1 -processdir d:\\temp -groupnames "ABC"',
function(err, stdout, stderr){
//callback(err)
if(err){
console.error(err);
}else {
console.log("should be no issue");
}
});
child.stdout.on('data', function(data) {
// Print out what being printed in the powershell
console.log(data);
});
child.stderr.on('data', function(data) {
//print error being printed in powershell
console.log('stderr: ' + data);
});
child.on('close',function(code){
// To check the result of powershell exit code
console.log("exit code is "+code);
if(code==0)
{
console.log("Powershell run successfully, exit code = 0 ")
}else {
console.log("ERROR, powershell exited with exit code = "+ code);
}
});
child.stdin.end();

Related

How to do Mongodb Backup with node js

I am wirting a mongodb auto backup code but i am stuck in some error: 'mongodump' is not recognized as an internal or external command.
can anyone help me out?
or is there another way to get auto backup with mongodb
exports.dbAutoBackUp = () => {
let cmd =
'mongodump --host ' +
dbOptions.host +
' --port ' +
dbOptions.port +
' --db ' +
dbOptions.database +
' --username ' +
dbOptions.user +
' --password ' +
dbOptions.pass +
' --out ' +
newBackupPath;
exec(cmd, (error, stdout, stderr) => {
console.log("Error : "+error)
console.log("Error 1: "+stdout)
console.log("Error 2: "+stderr)
if (this.empty(error)) {
// check for remove old backup after keeping # of days given in configuration.
if (dbOptions.removeOldBackup == true) {
if (fs.existsSync(oldBackupPath)) {
exec('rm -rf ' + oldBackupPath, err => {
console.log(err);
});
}
}
}
});
}
};
The error is probably because you are not in the directory where you have mongodb executable.
There are two ways to do it.
change your directory to mongodb's installation path
Add the mongodb executable to your environment variables
Path should be something like
{installation_directory}:\Program Files\MongoDB\Server\{version}\bin
For example
C:\Program Files\MongoDB\Server\4.2\bin

Unable to trigger NodeJS based BATCH/Exe file using jenkins

Im trying to execute the my batch/exe file through NodeJS script by using the:
var child_process = require('child_process');
i.e.
child_process.execFile For exe
child_process.exec For Batch file
When I'm trying to execute my scripts by using followings TWO method:
Triggering via CMD it will be get executed successfully.
Triggering via Jenkins it will NOT get executed.
In both cases directory is same.
I have been using the followings function for this purpose:
exports.exec_exe_file = exec_exe_file = function(exe)
//child_process.execFile(exe, function(error, stderr, stdout) {
child_process.exec(exe, function(error, stderr, stdout) { if (error) {
console.error('stderr', stderr); throw error; } //console.log('stdout',
stdout); });
}
Called as:
var autoit = __dirname + "\\autoit\\start_AutoitExe.bat";
//var autoit = __dirname + '\\autoit\\Script.exe';
exec_exe_file(autoit);

Having trouble running child process command

I am trying to execute a nodejs file called create-MySwitch.js through a child process in my main.js file.
this is the code for main.js
const exec = require('child_process').exec;
var cmdStr = 'node /home/pi/Desktop/lan-device/create-MySwitch.js';
exec(cmdStr,
{argv: {
port:8080,
uuid:'MyThing'
}},
(error, stdout, stderr)=>{
if (error) {
console.error('exec error: ${error}');
console.log(error);
return;
}
console.log('stdout: ${stdout}');
console.log('stderr: ${stderr}');
});
This is how I am attempting to access the arguments in the create-MySwitch.js file
var port_value = process.argv.port;
var uuid_value = process.argv.uuid;
The output is
stdout: ${stdout}
stderr: ${stderr}
when I run the command
node main.js
I do not think it's working because the output from executing the create-MySwitch.js file should be 'ready', but clearly is not being printed in the stdout variable from the child process.
Essentially, what I am trying to do is run the command 'node createMySwitch.js ', but instead of just typing this in to the command prompt I want to run that command using a child process.
I am doing all of this using the raspbian operating system.

nodejs command line module not giving stdout

I have set up a command line node module and when I run it one of the tasks is to start up the server and log to the console. However I find that although it starts up my server fine, it does not send the output to the console.
#! /usr/bin/env node
var userArgs = process.argv.slice(2);
var searchPattern = userArgs[0];
if(userArgs[0] === "start"){
var exec = require('child_process').exec;
exec('node ./server.js',
function(err, stdout, stderr) {
console.log('stdout: ', stdout);
console.log('stderr: ', stderr);
if (error !== null) {
console.log('exec error: ', error);
}
}
);
}
So if I npm link my module then run mymodule start it starts the server fine but as I mentioned no output to the console.
Whereas if I run simply node server.js I get the output which is server listening on http://localhost:5000.
From the documentation, regarding the callback you are passing to 'exec'
'callback' - Function called with the output when process terminates
From what I understand, the process has to be terminated before you see 'stdout:' and 'stderr:' (you would have to stop the node process).

Running Java keytool command from node on Windows

I'm trying to automate the creation on a keystore using Java. I'm running the child_process spawn function. For one thing, the keytool command response through the stderr channel which is odd, but it prompts me for the password. I'm unsure how to submit anything. If I call stdin.end() it kills the process.
var KEYTOOL_COMMAND = "C:\\Program Files\\Java\\jdk1.8.0_05\\bin\\keytool";
var ktArgs = ["-genkey", "-v", "-keystore", "test.keystore", "-alias", "test", "-keyalg", "RSA", "-keysize" ,"2048", "-validity", "10000"];
var spawn = require("child_process").spawn;
var cmd = spawn(KEYTOOL_COMMAND, ktArgs);
cmd.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
cmd.stderr.setEncoding('utf8');
cmd.stderr.on('data', function (data) {
cmd.stdin.write("password\\n\\r");
});
cmd.on('close', function (code) {
console.log('child process exited with code ' + code);
});
Here I'm to submit "password" as my password.
You're escaping your CR and LF, try this instead: cmd.stdin.write("password\r\n"); You might also try without the CR: cmd.stdin.write("password\n");

Resources