node.jsdirname

How can I produce __dirname pointing to the root directory from within an EJS module located in a subdirectory?


I am using EJS modules and would like to refer to all files with reference to the root directory. In the past, this would be __dirname, but per this description it is different. These instructions are helpful (https://blog.logrocket.com/alternatives-dirname-node-js-es-modules/) but I still cannot seem to find the right combination.

For example, I have test.mjs in the root directory and test2.mjs in the scripts directory (scripts/test2.mjs)

test.mjs

import {fileURLToPath} from 'url';
import { dirname } from "node:path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.log("test.mjs produces " + __dirname)

output

test.mjs produces rootdir

scripts/test2.mjs

import {fileURLToPath} from 'url';
import { dirname } from "node:path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.log("test2.mjs produces " + __dirname)

output

test2.mjs produces rootdir/scripts

Solution

  • The full path of the initial script that launched the app is in:

    process.argv[1]
    

    And, this is accessible from any script in your project, no matter where its located and it always returns the same filename.

    So, if you want to strip the filename off and get just the directory of that initial script, you can do this:

    import { dirname } from "node:path";
    
    const rootDir = dirname(process.argv[1]);
    

    Depending upon how your project's scripts are structured and which exact directory in that structure you want, you may want to go up or down from this directory, but it at least gives you a known and consistent location in your structure that is accessible from any script in the project.