How to get the cwd (current working directory) from a nodejs child process (in both windows and linuxish) - node.js

I'm trying to run a script via nodejs that does:
cd ..
doSomethingThere[]
However, to do this, I need to executed multiple child processes and carry over the environment state between those processes. What i'd like to do is:
var exec = require('child_process').exec;
var child1 = exec('cd ..', function (error, stdout, stderr) {
var child2 = exec('cd ..', child1.environment, function (error, stdout, stderr) {
});
});
or at very least:
var exec = require('child_process').exec;
var child1 = exec('cd ..', function (error, stdout, stderr) {
var child2 = exec('cd ..', {cwd: child1.process.cwd()}, function (error, stdout, stderr) {
});
});
How can I do this?

to start child with parent dir as cwd:
var exec = require('child_process').exec;
var path = require('path')
var parentDir = path.resolve(process.cwd(), '..');
exec('doSomethingThere', {cwd: parentDir}, function (error, stdout, stderr) {
// if you also want to change current process working directory:
process.chdir(parentDir);
});
Update: if you want to retrieve child's cwd:
var fs = require('fs');
var os = require('os');
var exec = require('child_process').exec;
function getCWD(pid, callback) {
switch (os.type()) {
case 'Linux':
fs.readlink('/proc/' + pid + '/cwd', callback); break;
case 'Darwin':
exec('lsof -a -d cwd -p ' + pid + ' | tail -1 | awk \'{print $9}\'', callback);
break;
default:
callback('unsupported OS');
}
}
// start your child process
// note that you can't do like this, as you launch shell process
// and shell's child don't change it's cwd:
// var child1 = exec('cd .. & sleep 1 && cd .. sleep 1');
var child1 = exec('some process that changes cwd using chdir syscall');
// watch it changing cwd:
var i = setInterval(getCWD.bind(null, child1.pid, console.log), 100);
child1.on('exit', clearInterval.bind(null, i));

If you want to get the current working directory without resorting to OS specific command line utilities, you can use the "battled-tested" shelljs library that abstract these things for you, while underneath using child processes.
var sh = require("shelljs");
var cwd = sh.pwd();
There you have it, the variable cwd holds your current working directory whether you're on Linux, Windows, or freebsd.

Just a thought, if you know the child process's PID, and have pwdx installed (likely on linux), you could execute that command from node to get the child's cwd.

I think the best bet is manipulating the options.cwd between calls to exec. in exec callback this.pwd and this.cwd might give you leverage for your implementations.

Related

How to out output live console.log with exec in node

Is there a way to run a command line command from within a node app and get the output to be live?
eg:
var exec = require('child_process').exec;
var fs = require('fs');
exec( 'nightwatch --config nightwatch_dev.json ', function( error, stdout, stderr ){
console.log( stdout );
});
or:
var exec = require('child_process').exec;
var fs = require('fs');
exec( 'rsync -avz /some/folder/ john#8.8.8.8:/some/folder/', function( error, stdout, stderr ){
console.log( stdout );
});
There are many many instances where it would be nice and easy to script something up in node but the output is only dumped to the terminal after the command has finished.
Cheers
J
If you want results as they occur, then you should use spawn() instead of exec(). exec() buffers the output and then gives it to you all at once when the process has finished. spawn() returns an event emitter and you get the output as it happens.
Examples here in the node.js doc for .spawn():

Get terminals PID out of Node.js APP [duplicate]

How to get the process name with a PID (Process ID) in Node.JS program, platform include Mac, Windows, Linux.
Does it has some node modules to do it?
Yes, built-in/core modules process does this:
So, just say var process = require('process'); Then
To get PID (Process ID):
if (process.pid) {
console.log('This process is your pid ' + process.pid);
}
To get Platform information:
console.log('This platform is ' + process.platform);
Note: You can only get to know the PID of child process or parent process.
Updated as per your requirements. (Tested On WINDOWS)
var exec = require('child_process').exec;
var yourPID = '1444';
exec('tasklist', function(err, stdout, stderr) {
var lines = stdout.toString().split('\n');
var results = new Array();
lines.forEach(function(line) {
var parts = line.split('=');
parts.forEach(function(items){
if(items.toString().indexOf(yourPID) > -1){
console.log(items.toString().substring(0, items.toString().indexOf(yourPID)));
}
})
});
});
On Linux you can try something like:
var spawn = require('child_process').spawn,
cmdd = spawn('your_command'); //something like: 'man ps'
cmdd.stdout.on('data', function (data) {
console.log('' + data);
});
cmdd.stderr.setEncoding('utf8');
cmdd.stderr.on('data', function (data) {
if (/^execvp\(\)/.test(data)) {
console.log('Failed to start child process.');
}
});
On Ubuntu Linux, I tried
var process = require('process'); but it gave error.
I tried without importing any process module it worked
console.log('This process is your pid ' + process.pid);
One more thing I noticed we can define name for the process using
process.title = 'node-chat'
To check the nodejs process in bash shell using following command
ps -aux | grep node-chat
cf official documentation https://nodejs.org/dist/latest-v10.x/docs/api/process.html#process_process_pid
the require is no more needed.
The good sample is :
console.log(`This process is pid ${process.pid}`);

How to respond to a command line promt with node.js

How would I respond to a command line prompt programmatically with node.js? For example, if I do process.stdin.write('sudo ls'); The command line will prompt for a password. Is there an event for 'prompt?'
Also, how do I know when something like process.stdin.write('npm install') is complete?
I'd like to use this to make file edits (needed to stage my app), deploy to my server, and reverse those file edits (needed for eventually deploying to production).
Any help would rock!
You'll want to use child_process.exec() to do this rather than writing the command to stdin.
var sys = require('sys'),
exec = require('child_process').exec;
// execute the 'sudo ls' command with a callback function
exec('sudo ls', function(error, stdout, stderr){
if (!error) {
// print the output
sys.puts(stdout);
} else {
// handle error
}
});
For the npm install one you might be better off with child_process.spawn() which will let you attach an event listener to run when the process exits. You could do the following:
var spawn = require('child_process').spawn;
// run 'npm' command with argument 'install'
// storing the process in variable npmInstall
var npmInstall = spawn('npm', ['install'], {
cwd: process.cwd(),
stdio: 'inherit'
});
// listen for the 'exit' event
// which fires when the process exits
npmInstall.on('exit', function(code, signal) {
if (code === 0) {
// process completed successfully
} else {
// handle error
}
});

NODEJS process info

How to get the process name with a PID (Process ID) in Node.JS program, platform include Mac, Windows, Linux.
Does it has some node modules to do it?
Yes, built-in/core modules process does this:
So, just say var process = require('process'); Then
To get PID (Process ID):
if (process.pid) {
console.log('This process is your pid ' + process.pid);
}
To get Platform information:
console.log('This platform is ' + process.platform);
Note: You can only get to know the PID of child process or parent process.
Updated as per your requirements. (Tested On WINDOWS)
var exec = require('child_process').exec;
var yourPID = '1444';
exec('tasklist', function(err, stdout, stderr) {
var lines = stdout.toString().split('\n');
var results = new Array();
lines.forEach(function(line) {
var parts = line.split('=');
parts.forEach(function(items){
if(items.toString().indexOf(yourPID) > -1){
console.log(items.toString().substring(0, items.toString().indexOf(yourPID)));
}
})
});
});
On Linux you can try something like:
var spawn = require('child_process').spawn,
cmdd = spawn('your_command'); //something like: 'man ps'
cmdd.stdout.on('data', function (data) {
console.log('' + data);
});
cmdd.stderr.setEncoding('utf8');
cmdd.stderr.on('data', function (data) {
if (/^execvp\(\)/.test(data)) {
console.log('Failed to start child process.');
}
});
On Ubuntu Linux, I tried
var process = require('process'); but it gave error.
I tried without importing any process module it worked
console.log('This process is your pid ' + process.pid);
One more thing I noticed we can define name for the process using
process.title = 'node-chat'
To check the nodejs process in bash shell using following command
ps -aux | grep node-chat
cf official documentation https://nodejs.org/dist/latest-v10.x/docs/api/process.html#process_process_pid
the require is no more needed.
The good sample is :
console.log(`This process is pid ${process.pid}`);

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