Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change working directory in my current shell context when running Node script

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.

like image 254
Jonovono Avatar asked Nov 06 '13 03:11

Jonovono


People also ask

How do I change the working directory in node JS?

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.

How do I get the current working directory in node JS?

There are two ways you can get the current directory in NodeJS: Using the special variable __dirname. Using the built-in method process. cwd()

What is 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.


2 Answers

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' 
like image 142
hexacyanide Avatar answered Oct 02 '22 11:10

hexacyanide


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.

like image 20
dthree Avatar answered Oct 02 '22 11:10

dthree