How to pass parameters from exec method to batch file using NodeJS - node.js

I am creating a child process in nodejs where it will compile and execute the java code. Below is the code
const exec = require('child_process').exec;
exec('C:/Development/vilearn/vilearn_node/src/my.bat', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
How can i pass the parameters from exec method to batch file.
Below is my batch file.
set path=C:\Program Files\Java\jdk1.8.0_111\bin
cd C:\Development\vilearn\vilearn_node\src
pwd
javac Hello.java
java Hello
As you can see from the above code i am using this batch file to compile the java code. Here i want to pass the path where java file exists and also the name of the java file from exec method so that it will b dynamic.
Please guide me
Help Appreciated!

Use ‘%*’ to select all parameters or ‘%1’, ‘%2’, ... to select a specific one
And use ‘spawn’ to load the batch then pass the params on the second param as an array of strings

You may pass parameters from the nodejs script like this,
const exec = require('child_process').exec;
const param1 = 'Hello.java';
const param2 = 'Hello';
exec(`"C:/Development/vilearn/vilearn_node/src/my.bat" "${param1}" "${param2}"`, (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
in your bat file,
set path=C:\Program Files\Java\jdk1.8.0_111\bin
cd C:\Development\vilearn\vilearn_node\src
pwd
javac %1
java %2
Use double quotes on your parameters to avoid splinting from space as 2 parameters

Related

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

How to run shell script file using nodejs?

I need to run a shell script file using nodeJS that executes a set of Cassandra DB commands. Can anybody please help me on this.
inside db.sh file:
create keyspace dummy with replication = {'class':'SimpleStrategy','replication_factor':3}
create table dummy (userhandle text, email text primary key , name text,profilepic)
You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.
hi.sh
echo "Hi There!"
node_program.js
const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
(error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
Here, when I run the nodejs file, it will execute the shell file and the output would be:
Run
node node_program.js
output
Hi There!
You can execute any script just by mentioning the shell command or shell script in exec callback.
You can execute any shell command using the shelljs module
const shell = require('shelljs')
shell.exec('./path_to_your_file')
you can go:
var cp = require('child_process');
and then:
cp.exec('./myScript.sh', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a command in your $SHELL.
Or go
cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a file WITHOUT a shell.
Or go
cp.execFile();
which is the same as cp.exec() but doesn't look in the $PATH.
You can also go
cp.fork('myJS.js', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a javascript file with node.js, but in a child process (for big programs).
EDIT
You might also have to access stdin and stdout with event listeners. e.g.:
var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
// handle stdout as `data`
});
Also, you can use shelljs plugin.
It's easy and it's cross-platform.
Install command:
npm install [-g] shelljs
What is shellJS
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix
shell commands on top of the Node.js API. You can use it to eliminate
your shell script's dependency on Unix while still keeping its
familiar and powerful commands. You can also install it globally so
you can run it from outside Node projects - say goodbye to those
gnarly Bash scripts!
An example of how it works:
var shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
Also, you can use from the command line:
$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo

Using bash with Node.js child_process using the shell option fails

The child process api can be used to execute shell script in node.js.
Im using the child_process.exec(command[, options], callback) function
as an option the user of exec can set the shell: '/path/to/shell' field to select the shell to be used. (Defaults to '/bin/sh')
Setting options to {shell: '/bin/bash'} does not make exec runt the command with bash.
I have verified this by issuing the command "echo $0" which prints "/bin/sh".
How can I use bash with child_process.exec through the shell option?
(My goal is to make use of my path definitions in bashrc, now when i try to use grunt the binary cannot be found. Setting the cwd, current working directory in the options dictionary works as expected)
----------------- UPDATE, example
'use strict';
var cp = require('child_process');
cp.exec('echo $0', { shell: '/bin/bash' }, function(err, stdout, stderr){
if(err){
console.log(err);
console.log(stderr);
}
console.log(stdout);
});
Output:
/bin/sh
which bash
prints:
/bin/bash
Might be in your setup or passing options incorrectly in your code. Since you didn't post your code, it's tricky to tell. But I was able to do the following and it worked (using node 4.1.1):
"use strict";
const exec = require('child_process').exec
let child = exec('time',{shell: '/bin/bash'}, (err, stdout, stderr) => {
console.log('this is with bash',stdout, stderr)
})
let child2 = exec('time',{shell: '/bin/sh'}, (err, stdout, stderr) => {
console.log('This is with sh', stdout, stderr)
})
The output will be:
this is with bash
real 0m0.000s
user 0m0.000s
sys 0m0.000s
This is with sh /bin/sh: 1: time: not found
I used time as the command since it's one that bash has and sh does not. I hope this helps!

how to use NodeJS to modify a file and save to a new one?

I have a plain text file named source.txt
I want to use a NodeJS script to do something to modify the content of the txt file and save as a new file, say output.txt
How do I do that?
I am expecting a command-line implementation, something like:
$node modify.js source.txt output.txt
Thanks!
Sync style:
// save as: uppercase.js
var fs = require('fs');
var input = process.argv[2];
var output = process.argv[3];
var content = fs.readFileSync(input, 'utf8');
content = content.toUpperCase();
fs.writeFileSync(output, content);
Run:
$node uppercase source.txt output.txt
Use Node.js's build in fs() function to read and write files to the local filesystem.
Basic read example:
fs.readFile('source.txt', function (err, data) {
if (err) throw err;
console.log(data);
});
Basic write example:
fs.writeFile('output.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
Note: ensure your Node instance (and the account it's being run under) has appropriate permissions to the read and write source/destination.

how do I make node child_process exec continuously

How to exec continuously? e.g. ls after cd?
I tried
exec = require('child_process').exec;
exec('cd ~/',
function(){
exec('ls'),
function(err, stdout, stderr){
console.log(stdout); // this logs current dir but not ~/'s
}
}
)
exec('cd ~/').exec('ls', function(err, stdout, stderr){
console.log(stdout);
})//this also fails because first exec returns a ChildProcess Object but not itself.
It is not possible to do this because exec and spawn creates a new process. But there is a way to simulate this. You can start a process with exec and execute multiple commands in the same time:
In the command line if you want to execute 3 commands on the same line you would write:
cmd1 & cmd2 & cmd3
So, all 3 commands run in the same process and have access to the context modified by the previous executed commands.
Let's take your example, you want to execute cd ../ and after that to execute dir and to view the previous directory list.
In cmd you shoud write:
cd../ & dir
From node js you can start a process with exec and to tell it to start another node instance that will evaluate an inline script:
var exec = require('child_process').exec;
var script = "var exec = require('child_process').exec;exec('dir',function(e,d,er){console.log(d);});";
script = '"'+script+'"';//enclose the inline script with "" because it contains spaces
var cmd2 = 'node -e '+script;
var cd = exec('cd ../ &'+cmd2,function(err,stdout,strerr)
{
console.log(stdout);//this would work
})
If you just want to change the current directory you should check the documentation about it http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
You can use nodejs promisify and async/await:
const { promisify } = require('util');
const exec = promisify(require('child_process').exec);
export default async function () {
const cpu = await exec('top -bn1');
const disk = await exec('df -h');
const memory = await exec('free -m');
const payload = {
cpu,
disk,
memory,
};
return payload
}
If you want to use cd first, better use process.chdir('~/'). Then single exec() will do the job.
You can call exec with cwd param like so:
exec('ls -a', {
cwd: '/Users/user'
}, (err, stdout) => {
if (err) {
console.log(err);
} else {
console.log(stdout);
}
})
But beware, cwd doesn't understand '~'. You can use process.env.HOME instead.

Resources