NodeJs child_process working directory

66,879

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
});
Share:
66,879

Related videos on Youtube

Jeroen De Dauw
Author by

Jeroen De Dauw

http://jeroendedauw.com/

Updated on July 05, 2022

Comments

  • Jeroen De Dauw
    Jeroen De Dauw almost 2 years

    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)

  • Jeroen De Dauw
    Jeroen De Dauw over 10 years
    Oh.. typo.. Now wondering how I did not spot that. Fixing the typo made the code work as expected.
  • Matt Westlake
    Matt Westlake about 6 years
    Doesn't seem to be working. On windows 10, not sure if that matters
  • vbtheory
    vbtheory almost 5 years
    @Matt Westlake I know I'm probably late but I think on Windows you need to execute cd instead of pwd like so var cmd = `cd foo/bar ⏎ ls`; var exec = require('child_process').exec; ...
  • Lennon McLean
    Lennon McLean over 3 years
    @Jeroen De Dauw lol, we've all been there
  • Clonkex
    Clonkex about 2 years
    @vbtheory Worth noting that there's also no ls on Windows (it's dir instead) and directory separators are backslashes, not forward slashes.
  • Amir Alam
    Amir Alam almost 2 years
    can i enter the windows path "c:\\"? its not working for me