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.
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. For Example: It can fail when the specified directory does not exist.
There are two ways you can get the current directory in NodeJS: Using the special variable __dirname. Using the built-in method process. cwd()
process. cwd() returns the current working directory, i.e. the directory from which you invoked the node command. __dirname returns the directory name of the directory containing the JavaScript source code file.
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'
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.
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