92

I am trying to execute a child process in a different directory then the one of its parent.

var exec = require('child_process').exec;

exec(
    'pwd',
    {
        cdw: someDirectoryVariable
    },
    function(error, stdout, stderr) {
        // ...
    }
);

I'm doing the above (though of course running "pwd" is not what I want to do in the end). This will end up writing the pwd of the parent process to stdout, regardless of what value I provided to the cdw option.

What am I missing?

(I did make sure the path passed as cwd option actually exists)

Mitch Talmadge
  • 4,638
  • 3
  • 26
  • 44
Jeroen De Dauw
  • 10,321
  • 15
  • 56
  • 79

2 Answers2

152

The option is short for current working directory, and is spelled cwd, not cdw.

var exec = require('child_process').exec;
exec('pwd', {
  cwd: '/home/user/directory'
}, function(error, stdout, stderr) {
  // work with result
});
hexacyanide
  • 88,222
  • 31
  • 159
  • 162
0

If you're on windows you might choke on the path separators. You can get around that by using the join function from the built-in Node.js path module. Here is @hexacyanide's answer but with execSync and join instead of exec (which doesn't block the event loop, but not always a huge deal for scripts) and Unix file paths (which are cooler and better than Window file paths).

const { execSync } = require('child_process');
const { join } = require('path');
exec('pwd', { cwd: path.join('home', 'user', 'directory') });
angstyloop
  • 117
  • 6