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!
Related
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
I am trying to execute two windows commands in sequence and get the result of the later one. Something like:
cd ${directory}
sfdx force:source:convert -d outputTmp/ --json
I have browsed and tried a bunch of third-party libraries, like node-cmd. But so far I haven't got any luck yet. As in node-cmd example:
cmd.get(
`cd ${directory}
sfdx force:source:convert -d outputTmp/ --json`,
function(err, data, stderr) {
This works very well on my macOS machine. But on Windows it tends to execute only the first command.
Is there anyway I can resolve this issue? Even some walk around for just cd {directory} + real command can be really helpful
You can try this:
const exec = require('child_process').exec;
exec(`cd dir
sfdx force:source:convert -d outputTmp/ --json`, (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
return;
}
console.log(stdout);
});
or by using && without backticks:
const exec = require('child_process').exec;
exec('cd dir && sfdx force:source:convert -d outputTmp/ --json', (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
return;
}
console.log(stdout);
});
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
I need to use node to generate diffs of some files. I have tried the diff npm package, and while that works great it is much less performant than the version of diff you will find in /usr/bin/.
When I try to use exec to run the diff command it always errors.
var childProcess = require('child_process');
var cmd = "diff /path/to/file1.txt /path/to/file2.txt";
childProcess.exec(cmd, (error, stdout, stderr) => {
if(error) {
console.log(error);
} else {
console.log(stdout);
}
});
The output:
{ [Error: Command failed: /bin/sh -c diff /path/to/file1.txt /path/to/file2.txt
]
killed: false,
code: 1,
signal: null,
cmd: '/bin/sh -c diff /path/to/file1.txt /path/to/file2.txt' }
If I run the command on the command line myself it works fine.
I've tried running /usr/bin/diff instead of just diff.
I've tried various different forms of quoting things.
Every other command I have tried, using the exact same files, has worked. cat, wc, etc.
Any thoughts?
Welp, I am answering my own question.
The diff command returns a failure exit code if it finds a difference. Therefore the console.log(stdout) call was never being reached.
If I ignore the error, everything works.
var childProcess = require('child_process');
var cmd = "diff /path/to/file1.txt /path/to/file2.txt";
childProcess.exec(cmd, (error, stdout, stderr) => {
console.log(stdout);
});
works like a charm.
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.