process.chdir() Method in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

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

Syntax

process.chdir(directory)

Parameters

  • directory – This will contain the name of the directory that will be updated in place of earlier directory name.

Example

Create a file with name – chdir.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below &Minus;

node chdir.js

chdir.js

 Live Demo

// Node.js program to demonstrate the use of process.chdir()

// Importing the process module
const process = require('process');

// Printing present working Directory
console.log("Present working directory: " + process.cwd());

try {
   // Updating with the New directory
   process.chdir('../tutorialspoint');
   console.log("Updated working directory is: " + process.cwd());
} catch (err) {
      // Printing error if any occurs
      console.error("error occured while " + "changing directory: " + err);
}

Output

C:\home\node>> node chdir.js
Present working directory: /home/mayankaggarwal/mysql-test
Updated working directory is: /home/mayankaggarwal/tutorialspoint

Example

Let's take a look at one more example.

 Live Demo

// Node.js program to demonstrate the use of process.argv

// Importing the process module
const process = require('process');

try {
   // Changing the directory with below namey
   process.chdir('../not/tutorialspoint');
   console.log("New Directory has been succesfully updated");
} catch (err) {
   // Printing error if occurs
   console.error("Error while changing directory", err);
}

Output

C:\home\node>> node chdir.js
Error while changing directory { Error: ENOENT: no such file or directory,
chdir '../not/tutorialspoint'
      at process.chdir (internal/process/main_thread_only.js:31:12)
      at Object.<anonymous> (/home/mayankaggarwal/mysql-test/process.js:9:9)
      at Module._compile (internal/modules/cjs/loader.js:778:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
      at Module.load (internal/modules/cjs/loader.js:653:32)
      at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
      at Function.Module._load (internal/modules/cjs/loader.js:585:3)
      at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
      at startup (internal/bootstrap/node.js:283:19)
      at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
   errno: -2,
   code: 'ENOENT',
   syscall: 'chdir',
   path: '../not/tutorialspoint' }
raja
Published on 20-May-2021 13:15:15
Advertisements