Change current directory with node

I am trying to write a command line utility in node.js. As one of the functions, it must change the current working directory of the shell from which it was called. Something like node.js version of cd . Can this be achieved? If so, how?


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

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

The problem is that process.chdir() works for the SCRIPT directory, not the SHELL directory. I need to somehow pass the current shell through a bash call to a node script and change the path to this shell in SCRIPT - creating a subshell will not solve the problem.

+6
source share
2 answers

In short: you cannot. The working directory is limited by the context of the process (and possibly of the child processes, but, of course, not of the parent processes). Therefore, the cdd of your Node process cannot propagate back to your shell process.

The general trick is for your Node application to print the working directory to stdout, and your shell will launch your Node application as follows:

 cd "$(node app)" 

A simple test case:

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

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

+7
source

To make this clear, you cannot change the pwd of the parent process. However, you can change the working directory and run the shell in this folder.


You need to use process.chdir() :

 console.log('Starting directory: ' + process.cwd()); try { process.chdir('/tmp'); console.log('New directory: ' + process.cwd()); } catch (err) { console.log('chdir: ' + err); } 

This example is taken from the manual. Here you can find the manual .

+4
source

Source: https://habr.com/ru/post/956628/


All Articles