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.
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'