[Node.js] Handle Relative Paths in a Node.js ESM Project with import.meta.url
Our CLI can be run from anywhere on the system but we have a critical error. The script is trying to find a data.json
file that is relative to where it is being called. This will throw an error if you aren't actually in the script directory.
The fix for this in an ECMAScript project like we are in is to use a import.meta.url
variable that will give use the directory that the script is executed in. We can append our data.json
to this path and call that throughout our script and we've fixed our error!
import {fileURLToPath} from "url";
import {dirname, join} from "path";
console.log(import.meta.url) // file:///Users/xxxxxx/Documents/learning/cli-tools/service.js
// in CommonJS, you can get the filename by __filename
console.log(fileURLToPath(import.meta.url)) // /Users/xxxxxx/Documents/learning/cli-tools/service.js
// in CommonJS, you can get the dirname by __dirname
console.log(dirname(fileURLToPath(import.meta.url))) // /Users/xxxxxx/Documents/learning/cli-tools
const __dirname = dirname(fileURLToPath(import.meta.url));
const dataFile = join(__dirname, "data.json");