149

I am trying to change the working directory of my Node.js script when it is run from a bin script. I have something like the following:

#!/usr/bin/env node
process.chdir('/Users')

When I then run this file with ./bin/nodefile, it exits, but the working directory of the current shell context has not changed. I have also tried shelljs, but that does not work either.

What is the best way to do this? I understand it's working but it's just in a separate process.

4
  • 1
    what evidence do you have that the cwd did not change? Remember that the paths used in require() and the cwd are two different things.
    – jeesty
    May 15, 2015 at 18:07
  • Is there a way to do this in Windows?
    – Phillip
    Oct 21, 2018 at 17:49
  • If you want to change a directory by executing nodejs script it won't work like that. I assume, the same as bash it runs in a subshell, and cannot change the parent shell working directory. As for bash it can be worked around with e.g. source script or running in the end of script $SHELL or exec bash. With nodejs I have no idea though. Nov 11, 2022 at 11:07
  • Everyone should heed @jeesty 's advice: even if you have changed this working directory, when you do things with require("fs") the working directory is not affected by this. Jan 2, 2023 at 18:04

7 Answers 7

187

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'
4
  • Oops. Ya, that is the command I am actually using. However, when I use it in a simple script it still does not seem to work (once the script exits I am still in the old directory) If I call process.cwd() it says I am in the directory I should be but my terminal if I call pwd says I am in something otherwise. Because it's a different process?
    – Jonovono
    Nov 6, 2013 at 3:57
  • 13
    The method changes the current working directory of the process, not the shell. As far as I know, changing the external cwd of a running process is quite complex and isn't recommended. What is your reason for wanting to do this? Nov 6, 2013 at 4:03
  • 5
    Hmm. Ok thanks. Well the reason I want to do this is because I am making a terminal app for organising my projects. So basically I want to be able to list my projects and easily change the current shell location to that. Now that I think about it, I am going to look into how z (github.com/rupa/z) does this. Although that is done in bash. I could perhaps do this in applescript?
    – Jonovono
    Nov 6, 2013 at 4:05
  • @hexacyanide thanks for adding was bothering because the changes were not aligned
    – EugenSunic
    Jul 4, 2020 at 19:17
38

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.

20

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.

14

Short answer: no (easy?) way, but you can do something that serves your purpose.

I've done a similar tool (a small command that, given a description of a project, sets environment, paths, directories, etc.). What I do is set-up everything and then spawn a shell with:

spawn('bash', ['-i'], {
  cwd: new_cwd,
  env: new_env,
  stdio: 'inherit'
});

After execution, you'll be on a shell with the new directory (and, in my case, environment). Of course you can change bash for whatever shell you prefer. The main differences with what you originally asked for are:

  • There is an additional process, so...
  • you have to write 'exit' to come back, and then...
  • after existing, all changes are undone.

However, for me, that differences are desirable.

2

Try this code:

const dirPath = path.join(__dirname, foldername);
process.chdir(dirPath);
1

you can use process.chdir.

The process.chdir() method changes the current working directory of the Node.js process or throws an exception if doing so fails (for instance, if the specified directory does not exist). document link: https://nodejs.org/api/process.html#processchdirdirectory

import { chdir, cwd } from 'node:process';

console.log(`Starting directory: ${cwd()}`);
try {
  chdir('/tmp');
  console.log(`New directory: ${cwd()}`);
} catch (err) {
  console.error(`chdir: ${err}`);
}
0
function cd(a, b) {
  var a_path_arry = a.split('/');
  var a_clear_path = [];
  var b_clear_path = [];
  a_path_arry.map((ele) => {
   if(ele != '') a_clear_path.push(ele);
  });

  b_path_arry = b.split('/');
  b_path_arry.map((ele) => {
    if(ele != '') b_clear_path.push(ele);
  });
  b_path_length = b_clear_path.length;

  for(var i=0;i<b_path_length;i++) {
    if(b_clear_path[i] == '.') {
        continue;
    } else if(b_clear_path[i] != '..') {
        a_clear_path.push(b_clear_path[i])
    }  
    else {
        a_clear_path.pop();            
    }
  }

  var path = '';
  a_clear_path.map((ele)=> {
    path += ele + '/';
  });

  console.log(path);

}

cd('a/b/c', './//d/e');
1
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck
    – nima
    Nov 2, 2022 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.