Solve - ReferenceError path is not defined in JavaScript

avatar

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.

index.js
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.

index.js
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.
package.json
{ "type": "module", // πŸ‘‡οΈ ... rest }

If you're using an older version of Node.js, you can use the require method.

index.js
const path = require('path'); // πŸ‘‡οΈ "/dist/index.html" console.log(path.join('/dist', 'index.html'));

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee