Resolve Magento 1 / Magento 2 root folder running inside the Magento tree but w/o Magento env, JavaScript module (.mjs) for NodeJs

PHOTO EMBED

Sat Jan 08 2022 06:00:50 GMT+0000 (Coordinated Universal Time)

Saved by @juliyvchirkov #javascript #nodejs #magento #document_root #resolve #module #mjs

import { realpathSync as realpath, accessSync as access, existsSync as exists } from 'fs'
import { dirname } from 'path'

/**
 * IIFE to resolve Magento document root
 * @returns <string> Returns Magento document root
 */
export const mageRoot = (() => {
    let mageRoot = dirname(realpath(import.meta.url.slice(7)))

    while (!(exists(`${ mageRoot }/app/Mage.php`) || exists(`${ mageRoot }/bin/magento`))) {
        mageRoot = dirname(mageRoot)
    }

    return mageRoot
})()
content_copyCOPY

https://gist.github.com/juliyvchirkov/2c5c8d54b182528e39d4565d1632f8ee#file-magentodocumentroot-mjs