Change working directory in my current shell context when running Node script Change working directory in my current shell context when running Node script javascript javascript

Change working directory in my current shell context when running Node script


The correct way to change directories is actually with process.chdir(directory). Here's an example from the documentation:

console.log('Starting directory: ' + process.cwd());try {  process.chdir('/tmp');  console.log('New directory: ' + process.cwd());}catch (err) {  console.log('chdir: ' + err);}

This is also testable in the Node.js REPL:

[monitor@s2 ~]$ node> process.cwd()'/home/monitor'> process.chdir('../');undefined> process.cwd();'/home'


There is no built-in method for Node to change the CWD of the underlying shell running the Node process.

You can change the current working directory of the Node process through the command process.chdir().

var process = require('process');process.chdir('../');

When the Node process exists, you will find yourself back in the CWD you started the process in.


What you are trying to do is not possible. The reason for this is that in a POSIX system (Linux, OSX, etc), a child process cannot modify the environment of a parent process. This includes modifying the parent process's working directory and environment variables.

When you are on the commandline and you go to execute your Node script, your current process (bash, zsh, whatever) spawns a new process which has it's own environment, typically a copy of your current environment (it is possible to change this via system calls; but that's beyond the scope of this reply), allowing that process to do whatever it needs to do in complete isolation. When the subprocess exits, control is handed back to your shell's process, where the environment hasn't been affected.

There are a lot of reasons for this, but for one, imagine that you executed a script in the background (via ./foo.js &) and as it ran, it started changing your working directory or overriding your PATH. That would be a nightmare.

If you need to perform some actions that require changing your working directory of your shell, you'll need to write a function in your shell. For example, if you're running Bash, you could put this in your ~/.bash_profile:

do_cool_thing() {  cd "/Users"  echo "Hey, I'm in $PWD"}

and then this cool thing is doable:

$ pwd/Users/spike$ do_cool_thingHey, I'm in /Users$ pwd/Users

If you need to do more complex things in addition, you could always call out to your nodejs script from that function.

This is the only way you can accomplish what you're trying to do.