How to excute .bat script on windows from node js - windows

I have node js file which will excute my bat file. I tried using exec of node js child-process module but no luck
Let me share you my node js script:
var startTime = '2014-11-27 17:0:42';
var threadName = '<Thread 0>';
var categoryName ='AlarmCategory';
var alarmLevel = 'Fatal';
var alarmCategory = 'OS';
var alarmMessage = 'corrupt';
var cp = require('child_process');
msg = cp.exec('handler.bat' +" " + startTime ,function (error, stdout, stderr) {
if (error) {
console.log(error.stack);
console.log('Error code: '+error.code);
console.log('Signal received: '+error.signal);
}
console.log('Child Process STDOUT: '+stdout);
console.log('Child Process STDERR: '+stderr);
});
My bat script . This script takes input parms and echos.
#echo off
set startTime=%1
set thread=%2
set categoryName=%3
set alarmLevel=%4
set alarmCategory=%5
set alarmMessage=%6
Echo #####################
Echo This tool will help you get the users info
Echo #####################
Echo hi %arg1%
For now i am printing only one arg.
Error i am getting :
"C:\Program Files (x86)\JetBrains\WebStorm 8.0.4\bin\runnerw.exe" "C:\Program Files\nodejs\node.exe" test\test_cmd.js
Error: Command failed: 'handler.bat' is not recognized as an internal or external command,
operable program or batch file.

I resolved my issue. I am using execFile() function now since i also need to pass arguments. It is very important to note that when you use execute command using execFile() make sure you set the "cwd" option in command of exeFile(). Since it looks for the child process file and it does not find the file. Setting full path directly for .bat file do not work .
I did like this ,
msg = cp.execFile('handler.bat' ,[startTime,threadName] ,{cwd:'/Node Js/baflog/sigma-logger/test'},function (error, stdout, stderr) {
.... ..
...
}

Related

Running bash script from Deno

Let’s say I’ve got this super useful and advanced bash script:
#!/usr/bin/env bash
echo What is your name?
read name
echo What is your age?
read age
When I try to run it from Deno with a simple script like this:
const process = Deno.run({
cmd: [`./bash.sh`],
stdin: "piped",
stdout: "piped",
});
const decoder = new TextDecoder();
const output = await process.output()
const parsed = decoder.decode(output);
console.log(parsed);
It returns nothing, but if I simplify the Deno script to the first line of the bash script it returns the output just fine
const process = Deno.run({
cmd: [`echo`, `What is your name?`],
stdin: "piped",
stdout: "piped",
});
const decoder = new TextDecoder();
const output = await process.output()
const parsed = decoder.decode(output);
console.log(parsed);
Why is this? I’d assume since the start of the bash file and the single line command both start with echo it would return the same result twice
Version 1.5 of deno added the prompt function which allows you to completely remove the need for shelling out to a different program and handling inter-process communication via stdin/stdout.
let name: string | null = null;
let age: string | null = null;
while (name === null) {
name = prompt("What is your name?");
}
while (age === null) {
age = prompt("What is your age?");
}
console.log(`you are ${name}, ${age}yo`);
Your code is telling Deno to set up the subprocess to expect piped stdin -- but never providing it any content on stdin! Consequently, it hangs in the very first read.
If we take that out (letting stdin be passed through from the parent process), and do in fact answer the two prompts on the parent process's stdin, everything works perfectly:
deno run --allow-run run-bash.js <<'EOF'
A Nony Mouse
3
EOF
...with run-bash.js containing:
const process = Deno.run({
cmd: [`./bash.sh`],
stdout: "piped",
});
const decoder = new TextDecoder();
const output = await process.output()
const parsed = decoder.decode(output);
console.log(parsed);
...and your bash.sh unchanged. output thus captures the two prompts (What is your name? and What is your age?), and forwards them to the javascript interpreter's stdout as-requested.
You have to call bash to call your script
( of course with --allow-run option )
like :
const process = Deno.run({
cmd: ["bash","bash.sh"],
stdin: "piped",
stdout: "piped",
});
const decoder = new TextDecoder();
const output = await process.output()
const parsed = decoder.decode(output);
console.log(parsed);

How to get CMD output in HTA file within JavaScript

I run some CMD commands in my HTA file like
<script>
var WShell = new ActiveXObject('WScript.Shell');
WShell.run('cmd /c the_first_command');
WShell.run('cmd /c the_second_command');
</script>
and the first command may need a time to be fully executed, for example a few seconds
I need to run the next command only after the CMD output says that the previous task is fully completed.
As I understand, after the first command I can run an interval for example
var timer = setInterval(function() {
var cmd_output_of_the_first_command = ???;
if(~cmd_output_of_the_first_command.indexOf('A text about the task is completed')) {
clearInterval(timer);
WShell.run('cmd /c the_second_command');
}
}, 500);
So the question is how to get the CMD output?
Ok, I've found the answer:
var WShell = new ActiveXObject('WScript.Shell');
var WShellExec = WShell.Exec('cmd /c the_first_command');
var WShellResult = WShellExec.StdOut.ReadAll();
if(~WShellResult.indexOf('A text about the task is completed')) {
WShell.Run('cmd /c the_second_command');
}
No need in any interval
OR
just
execute CMD synchronously one by one without the need to check CMD output
WShell.Run('cmd /c the_first_command', 0, true);
WShell.Run('cmd /c the_second_command', 0, true);

D: executeShell on Windows to run another program not returning immediately

I'm using D as a scripting language for Windows 7 console stuff to automate boring tasks. One of my scripts (open.exe) is supposed to allow me to open stuff from the command line without me having to specify which program I use (I have a configuration file with this stuff). Now, I use executeShell to do this, and call something like start [name of program I want to use] [name of input file]. If I do this directly from the shell, it returns immediately, but if I do it using my D script, it doesn't return until the program that it opens is closed. What should I do to allow it to return immediately?
For reference purposes, this is the business logic of my script (the main method just does some argument parsing for piping purposes):
immutable path = "some//path//going//to//config//file.conf";
void process(string input) {
string extension = split(input,".")[1]; //get file extension from input
auto config = File(path,"r"); auto found = false;
while (!config.eof()){
auto line = chomp(config.readln());
if (line[0]!='#') { //skip comment lines
auto divided = split(line, ":");
if (divided[0] == extension) {
found = true;
auto command = "start " ~ divided[1] ~ " " ~ input;
auto result = executeShell(command);
//test for error code and output if necessary
writeln(result.output);
}
}
}
if (!found)
writeln("ERROR: Don't know how to open " ~ input);
}
From the top of the std.process documentation:
Execute and wait for completion, collect output - executeShell
The Windows start program spawns a process and exits immediately. D's executeShell does something else. If you'd like to spawn another program, use the appropriate functions: spawnProcess or spawnShell.

Node.js Shell Script And Arguments

I need to execute a bash script in node.js. Basically, the script will create user account on the system. I came across this example which gives me an idea how to go about it. However, the script itself needs arguments like the username, the password and the real name of the user. I still can't figure out how to pass those arguments to the script doing something like this:
var commands = data.toString().split('\n').join(' && ');
Does anyone have an idea how I can pass those arguments and execute the bash script within node.js over an ssh connection.
thanks
See the documentation here. It is very specific on how to pass command line arguments. Note that you can use exec or spawn. spawn has a specific argument for command line arguments, while with exec you would just pass the arguments as part of the command string to execute.
Directly from the documentation, with explanation comments inline
var util = require('util'),
spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']); // the second arg is the command
// options
ls.stdout.on('data', function (data) { // register one or more handlers
console.log('stdout: ' + data);
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('exit', function (code) {
console.log('child process exited with code ' + code);
});
Whereas with exec
var util = require('util'),
exec = require('child_process').exec,
child;
child = exec('cat *.js bad_file | wc -l', // command line argument directly in string
function (error, stdout, stderr) { // one easy function to capture data/errors
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
Finally, note that exec buffers the output. If you want to stream output back to a client, you should use spawn.
var exec = require('child_process').exec;
var child = exec('cat *.js | wc -l', function(error, stdout, stderr) {
if (error) console.log(error);
process.stdout.write(stdout);
process.stderr.write(stderr);
});
This way is nicer because console.log will print blank lines.
You can use process.argv. It's an array containing the command line arguments. The first element will be node the second element will be the name of the JavaScript file. All next elements will be any additional command line you given.
You can use it like:
var username = process.argv[2];
var password = process.argv[3];
var realname = process.argv[4];
Or iterate over the array. Look at the example: http://nodejs.org/docs/latest/api/all.html#process.argv

cscript - print output on same line on console?

If I have a cscript that outputs lines to the screen, how do I avoid the "line feed" after each print?
Example:
for a = 1 to 10
WScript.Print "."
REM (do something)
next
The expected output should be:
..........
Not:
.
.
.
.
.
.
.
.
.
.
In the past I've used to print the "up arrow character" ASCII code. Can this be done in cscript?
ANSWER
Print on the same line, without the extra CR/LF
for a=1 to 15
wscript.stdout.write a
wscript.stdout.write chr(13)
wscript.sleep 200
next
Use WScript.StdOut.Write() instead of WScript.Print().
WScript.Print() prints a line, and you cannot change that. If you want to have more than one thing on that line, build a string and print that.
Dim s: s = ""
for a = 1 to 10
s = s & "."
REM (do something)
next
print s
Just to put that straight, cscript.exe is just the command line interface for the Windows Script Host, and VBScript is the language.
I use the following "log" function in my JavaScript to support either wscript or cscript environment. As you can see this function will write to standard output only if it can.
var ExampleApp = {
// Log output to console if available.
// NOTE: Script file has to be executed using "cscript.exe" for this to work.
log: function (text) {
try {
// Test if stdout is working.
WScript.stdout.WriteLine(text);
// stdout is working, reset this function to always output to stdout.
this.log = function (text) { WScript.stdout.WriteLine(text); };
} catch (er) {
// stdout is not working, reset this function to do nothing.
this.log = function () { };
}
},
Main: function () {
this.log("Hello world.");
this.log("Life is good.");
}
};
ExampleApp.Main();

Resources