Constructing an absolute file path with process.cwd()

2/15/2025 12:00:00 AM

joe-jngigi

Let's break down the process of constructing the file path

We get to the root of the project using the process.cwd(). This function returns the current working directory of the Node.js process. When running a next.js application, this is usually the root directory of the project.

or example, if your project is located at /Users/username/my-project, then process.cwd() will return that exact string.


  console.log("PROCESS",process.cwd())

  //This should give me my current working directory
  //------------------------------------------------
  //---PROCESS /media/user/user/active_projects/joe_jngigi_beta/next15---

We then use path.join() function to safely concatenate multiple path segments into one single path string. This function automatically handles the correct path separators for the respective operations systems, in his case / for unix systems, and the \ for the the windows system

Combining the Segments


path.join(process.cwd(), "/docs", "blog.md")

The first argument is the absolute path returned by process.cwd(), which is joined with the second argument is "/docs"

Typically, if you intend docs to be a directory inside your project root, you might want to use "docs" (without the leading slash). This is because a leading slash makes the path segment absolute, which in some cases can override the previous segments.

(Though I added to mine, will be handled by path.join)