Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
101
rated 0 times [  106] [ 5]  / answers: 1 / hits: 20993  / 11 Years ago, thu, october 24, 2013, 12:00:00

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.


More From » node.js

 Answers
32

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.


[#74766] Wednesday, October 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristinsonjab

Total Points: 364
Total Questions: 98
Total Answers: 98

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
kristinsonjab questions
Fri, Mar 4, 22, 00:00, 2 Years ago
Fri, Jan 22, 21, 00:00, 3 Years ago
Fri, Aug 14, 20, 00:00, 4 Years ago
;