child_process working directory - node.js

I am trying to execute a child process in a different directory then the one of its parent.
var script = "drush language-add cn";
var folderDrush = "/data/www/sites/site_cn_country";
exec(script, {cwd:folderDrush} , function (err, stdout, stderr) {
if(err) {
sendErr("drush", stderr);
sendCommand(script);
sendCheck("drush", false);
}
});
This script returns:
The drush command 'language-add cs' could not be found. Run drush [31;40m[1m[error][0m cache-clear drush to clear the commandfile cache if you have installed new extensions.
But when I execute manualy, drush language-add work fine.
I test there commands too :
pwd : /data/www/sites/site_cn_country
id -u -n : root
ll : Command not found (why ? manually work...)
echo $SHELL : /bin/bash

This is not a direct answer, but you could change path before running the command:
var script = "cd /data/www/sites/site_cn_country && drush language-add cn";

Related

How to specify folder location using `cd` command inside exec function?

Instead of specifying root of file for execution in a remote server, how we can use cd command in exec() in nodejs.What i am done is like this.
var command_part1 = `ssh -p 22 root#ip`;
var command_part2 = `python3 test.py ${input}`;
var folderPath = `/root/folder/`;
var child = exec(`${command_part1} && cd ${folderPath} && ${command_part2}` , function (error, stdout, stderr) {
if (error !== null) {
callback(error)
} else {
callback();
}
});
But this code is not working, when i am executing this command locally,ssh login only is happening, further commands are not working.How can i make this working ? I dont want to specify the folder path like python3 /root/folder/test.py ${input};
Thank You Inadvance
Try this code,
`var command = `sshpass -p givePassword ssh -o "StrictHostKeyChecking no" root#ip "cd ${folderPath} && ${command_part2}"`
sshpass is a simple and lightweight command line tool that enables us to provide password (non-interactive password authentication) to the command prompt itself, so that automated shell scripts can be executed

Node js - how to execute two windows commands in sequence and get the output

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

Changing command prompt directory from Node.js script

I'm trying to change the directory of terminal using with Node.js program but not able to achieve it. Script is run as node app.js dir_name so first I'm creating the directory and then trying to change into that directory using cd command. Directory is created but the directory for terminal is not changed.
#!/usr/bin/env node
var platform = process.platform;
var figlet = require('figlet');
var chalk = require('chalk');
if(process.argv.length < 3){
console.log(
chalk.green(
figlet.textSync('mdcd', { horizontalLayout: 'full' })
)
);
console.log(chalk.red("Please provide a directory name"));
}else{
if(platform.includes("win")){
//console.log("Its Windows");
}else {
var exec = require('child_process').exec;
var command_1 = "mkdir "+process.argv[2];
var command_2 = "cd "+process.cwd()+"/"+process.argv[2];
exec(command_1, function (error, stdout, stderr) {
if(error){
console.log("Something bad happened"+error);
}else {
exec(command_2, function (error, stdout, stderr) {
if(error){
console.log("Something bad happened"+error);
}
});
}
});
}
}
command prompt directory from Node.js script
You cannot change the command prompt directory. Basically you have the process tree:
cmd / term
| -> NodeJs
You shouldn't change the working dir for cmd. However there are command you can execute to change the working dir of any process e.g. https://unix.stackexchange.com/a/282009
More
You can however change the the working dir for the nodejs process (which is what I suspect you want to do) using process.chdir https://nodejs.org/api/process.html#process_process_chdir_directory

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!

Resources