How to Set the Current Working Directory of a Node.js Program
In this tutorial, we will explore how to set the current working directory of a Node.js program. This is particularly useful when you need to serve an index.html
HTML page using Node.js without any dependencies.
I encountered this issue while working on a Node.js script. Initially, I set relative paths to reference some files in the local filesystem, like this:
1 | '../../dev/file.md' |
Everything worked fine when I ran the program from its folder. However, running the file from another folder, such as the parent folder, caused the relative links to break.
To fix this issue, you can use the following code at the beginning of your program:
1 | const process = require('process'); |
The process.chdir()
method sets the current working directory of the Node.js process to __dirname
, which represents the parent folder path of the current file.
Using this approach ensures that your relative paths remain correct regardless of the program’s execution location.
Tags: Node.js, current working directory, file system, relative paths