Borislav Hadzhiev
Tue Oct 19 2021·1 min read
Photo by Christopher Carson
The "ReferenceError: path is not defined" occurs when we use the path
module
without importing it in a Node.js application. To solve the error, make sure to
import the path module before using it - import path from 'path'
.
To solve the error, import the path
module before using it.
import path from 'path'; // 👇️ "/dist/index.html" console.log(path.join('/dist', 'index.html'));
If you need access to the directory name of a path, don't use the __dirname
global variable because it's not available when using ES6 modules and you would
get the error - "__dirname is not defined".
Here's how to get the directory name using the ES6 modules syntax.
import path from 'path'; import {fileURLToPath} from 'url'; const filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(filename); // 👇️ "/home/john/Desktop/javascript" console.log('directory-name️', __dirname); // 👇️ "/home/john/Desktop/javascript/dist/index.html" console.log(path.join(__dirname, '/dist', 'index.html'));
We used the dirname()
method instead of the __dirname
global to get the
directory name.
type
property to module
in your package.json
file.{ "type": "module", // 👇️ ... rest }
If you're using an older version of Node.js, you can use the require
method.
const path = require('path'); // 👇️ "/dist/index.html" console.log(path.join('/dist', 'index.html'));