process.chdir() Method in Node.js

The process.chdir() method changes the current working directory of the Node.js process. It throws an exception if the operation fails (such as when the specified directory doesn't exist) but returns no value on success.

Syntax

process.chdir(directory)

Parameters

  • directory - A string containing the path to the directory you want to change to.

Return Value

This method returns undefined on success and throws an error if the directory change fails.

Example 1: Successful Directory Change

// Node.js program to demonstrate process.chdir()
const process = require('process');

// Print current working directory
console.log("Current directory: " + process.cwd());

try {
    // Change to parent directory
    process.chdir('../');
    console.log("New directory: " + process.cwd());
} catch (err) {
    console.error("Error changing directory: " + err.message);
}
Current directory: /home/user/myproject
New directory: /home/user

Example 2: Handling Directory Not Found Error

// Attempting to change to non-existent directory
const process = require('process');

console.log("Current directory: " + process.cwd());

try {
    // This will fail - directory doesn't exist
    process.chdir('../nonexistent/directory');
    console.log("Directory changed successfully");
} catch (err) {
    console.error("Error: " + err.message);
    console.log("Directory unchanged: " + process.cwd());
}
Current directory: /home/user/myproject
Error: ENOENT: no such file or directory, chdir '../nonexistent/directory'
Directory unchanged: /home/user/myproject

Common Use Cases

  • Changing to a specific directory before performing file operations
  • Navigating to configuration directories during application startup
  • Setting up the working directory for child processes

Key Points

  • Always wrap process.chdir() in a try-catch block to handle errors
  • The method throws an ENOENT error if the directory doesn't exist
  • Use process.cwd() to check the current directory before and after changes
  • Directory paths can be relative (../) or absolute (/home/user/)

Conclusion

The process.chdir() method is essential for directory navigation in Node.js applications. Always handle potential errors with try-catch blocks when changing directories.

Updated on: 2026-03-15T23:19:00+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements