ReferenceError: path is not defined in JavaScript – How to fix it?

“ReferenceError: path is not defined” in JavaScript

“ReferenceError: path is not defined” is an error you may encounter when building a Node.js application. This article will show you how to fix it. Read on it now.

When does the “ReferenceError: path is not defined” in JavaScript appear?

The path module provides a way of working with directories and file paths.

Example:

const path = require('path');

// returns the last part of the path
const filename = path.basename('/home/user/dir/demo_path.js');

console.log(filename);

Output:

demo_path.js

In the above example, we use the basename() method, which returns the last part of the path.

Syntax:

path.basename (path, suffix)

Parameter:

  • path: a directory path
  • suffix: an optional suffix to remove

“ReferenceError: path is not defined” appears when you try to use the ‘path’ module without importing it in your Node.js application. Let’s take a look at the simple example below to understand.

Example:

const filename = path.basename('/home/user/dir/demo_path.js');
console.log(filename);

Output:

ReferenceError: path is not defined

How to fix this error?

Using the require function

The require function reading a JavaScript file, then executing the file, and finally returning the exports object.

The syntax for require the path module is as follows:

const path = require('path');

Here is a specific example:

const path = require('path');

const parse = {
  root: '/',
  dir: '/home/user/dir',
  base: 'demo_path.js',
  ext: '.js',
  name: 'demo_path'
}

//returns a path string from the 'parse' object
const format = path.format(parse);

console.log(format);

Output:

/home/user/dir/demo_path.js

In the above example, we provide an object whose properties represent the key elements of the path. We then use the path.format() method to get a path string from that object.

Any JavaScript object having the following properties: dir <string>, root <string>, base <string>, name <string> and ext <string>.

The path.format() method returns a path string from an object.

Using import syntax

If the version of nodejs you are using supports ES6 features, you can use the import syntax as follows:

import path from 'path';

Next you need to add “type”: “module” to your package.json, Node.js will treat your file like an ES module.

Example:

import path from 'path';

//returns the last part of the path
const filename = path.basename('/home/user/dir/demo_path.js');

console.log(filename);
{
  "type": "module",
}

Output:

demo_path.js

Summary

This article has shown how to fix the ReferenceError: path is not defined in JavaScript. I hope the information in this article will be helpful to you. If you have any problems, please comment below. I will answer as possible. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *