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_thing
Hey, 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.