Node.js
Resolve a file relative to an ES module
Resolve a resource with new URL and import.meta.url when it belongs beside an ES module. This avoids depending on the directory from which the user launched Node.js.
Worked example
Node.js example · save as example.mjs and run node example.mjs
import {fileURLToPath} from "node:url";
const resource = new URL("./settings.json", import.meta.url);
console.log(resource.protocol);
console.log(fileURLToPath(resource).endsWith("settings.json"));How it works
Import.meta.url identifies the current module as a URL. Resolving a relative URL against it locates a neighboring resource consistently even when process.cwd points somewhere else. Node filesystem APIs commonly accept file URL objects directly.
Limits and mistakes
Do not use URL.pathname as a general filesystem conversion: spaces, encoded characters, and Windows paths require correct handling. Use fileURLToPath when a string path is actually needed. The example computes a path but does not create the resource.
Check the result
Expect file: and true. Launch the script from another working directory and confirm the resource still resolves beside the module.
Sources
Reference documentation for the behavior used in this guide: