Set the current working directory of a Node.js program
By Flavio Copes
Learn how to set the current working directory of a Node.js program with process.chdir(__dirname) so your relative file paths keep working from any folder.
To set the current working directory of a Node.js program, call process.chdir() with the path you want. I use it to make relative file paths reliable, and here’s the story of why.
I had this problem with a Node.js script I wrote.
I had set relative paths to reference some files in the local filesystem, like this:
../../dev/file.md
and if I ran the program from the folder it was in, no problem.
But if I ran the file from another folder, for example the parent folder, the relative links would break.
That’s because relative paths are resolved against the current working directory, the folder your terminal was in when you launched node. Not the folder the script lives in. You can check it at any time with process.cwd().
The fix
At the beginning of the program, I set:
const process = require('process')
process.chdir(__dirname)
This sets the current working directory of the process to __dirname, which points to the folder containing the current file.
(process is a global in Node.js, so the require line is optional. I like having it explicit.)
Say the script lives in /Users/flavio/scripts and I run it from my home folder:
console.log(process.cwd()) // /Users/flavio
process.chdir(__dirname)
console.log(process.cwd()) // /Users/flavio/scripts
Now every relative path in the program resolves from the script’s folder, no matter where I launch it from.
Things to watch out for
process.chdir() throws if the directory doesn’t exist, with an ENOENT error. With __dirname that can’t happen, but keep it in mind if you pass a user-provided path.
The bigger caveat: the change affects the entire process. Every module, every library you imported. If some dependency expects the original working directory, you’ve just changed it under its feet.
For a small standalone script like mine, that’s fine. In a larger app, I’d build absolute paths instead, without touching the working directory:
const path = require('path')
const file = path.join(__dirname, '../../dev/file.md')
Same result for that one path, no process-wide side effects.
Related posts about node: