Handle Relative Paths in a Node.js ESM Project with import.meta.url

Share this video with your friends

Send Tweet

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!

~ 2 years ago

There's an easier way according to the docs: const dataFile = new URL("./data.json", import.meta.url); see: https://nodejs.org/api/esm.html#importmetaurl (correct me if I'm wrong, trying learn)