nodejs change dir

Changing Directory in Node.js

Node.js provides an fs module that allows you to work with the file system in a non-blocking way. One of the functions provided by this module is fs.readdir(), which allows you to read the contents of a directory.

Changing the Current Working Directory

To change the current working directory in Node.js, you can use the process.chdir() method. This method changes the current working directory of the Node.js process to the specified directory.


// Change the current working directory to 'myDirectory'
process.chdir('myDirectory');

The process.chdir() method takes a single argument, which is the path of the directory to which you want to change.

Using the fs Module to Change the Directory

You can also use the fs module to change the current working directory in Node.js. The fs module provides a method called fs.realpath(), which resolves relative paths to absolute paths. You can use this method to get the absolute path of the directory you want to change to, and then use process.chdir() to change the current working directory.


const fs = require('fs');

// Get the absolute path of 'myDirectory'
const absolutePath = fs.realpathSync('myDirectory');

// Change the current working directory to 'myDirectory'
process.chdir(absolutePath);

The fs.realpathSync() method takes a single argument, which is the path of the directory you want to get the absolute path of.

Summary

  • To change the current working directory in Node.js, you can use the process.chdir() method.
  • You can also use the fs module to change the directory by getting the absolute path of the directory using fs.realpath() and then using process.chdir().

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe