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.
There are two ways you can get the current directory in NodeJS: Using the special variable __dirname. Using the built-in method process. cwd()
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With