Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change current directory with node

I'm trying to write a command line utility in node.js. As one of the features it should change the current working directory of the shell it was called from. Something like node.js version of cd. Is it possible to achieve this? If so, how?

 


 

To clarify, I'd like to be able to change the current directory in the terminal window by running the script.

/some/path> ...
/some/path> nodecd /other/path
/other/path> ...

The problem is that process.chdir() works for the SCRIPT directory, not for the SHELL directory. I need to be able to somehow pass the current shell through the bash invocation to node script, and alter the path of that shell within the script - creating a subshell won't solve the problem.

like image 993
Hubert OG Avatar asked Oct 24 '13 10:10

Hubert OG


People also ask

How do I get the current working directory in node JS?

There are two ways you can get the current directory in NodeJS: Using the special variable __dirname. Using the built-in method process. cwd()

Which of the following codes is used to change the current working directory of the process or throw an exception if that fails?

chdir() method is used for changing the current directory of the Node. js process. It will throw an exception if any error occurs or the process fails, but will not return any response on success.


1 Answers

In short: you can't. The working directory is limited to the context of a process (and perhaps child processes, but certainly not parent processes). So the cwd of your Node process cannot propagate back to your shell process.

A common trick is to have your Node app print the working directory to stdout, and have your shell run your Node app like this:

cd "$(node app)"

A simple test case:

// app.js
console.log('/tmp');

And if you create a shell alias/function for it, it should be relatively painless.

like image 87
robertklep Avatar answered Oct 01 '22 18:10

robertklep