Solve - ReferenceError path is not defined in JavaScript


Borislav Hadzhiev

Tue Oct 19 20211 min read

Solve - ReferenceError path is not defined #

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'.

referenceerror path is not defined

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.

Note that at the time of writing to use ES6 module imports, you have to set thetype 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'));
Use the search field on my Home Page to filter through my more than 1,000 articles.