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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)