NodeJS Path Module
NodeJS path module is the builtin module of nodeJS ,We use the path module to work with the file path, By requiring the path module using require function we can directly import the path module in the our project. The module returns an object that we are storing in the path constant.
const path = require('path');
Properties and Methods of the path module
basename()
Returns the last path / filename form the path
const path = require('path');
let basename = path.basename('./middleware/login.js')
console.log(basename);
//Output - login.js
join()
Joints all the arguments together and create a path.
const path = require('path');
let fullPath = path.join('codelearningpoint.com','/', 'tutorial','/', 'path.js');
console.log(fullPath);
//Output - codelearningpoint.com/tutorial/path.js
extname()
returns the extension of the file
const path = require('path');
let extname = path.extname('./middleware/login.js');
console.log(extname);
//Output - .js
parse()
parse the string path and parse it into a path object
const path = require('path');
let parsedURL = path.parse('./middleware/login.js');
console.log(parsedURL);
/*Output -
{
root: '',
dir: './middleware',
base: 'login.js',
ext: '.js',
name: 'login'
}
*/
dirname()
returns the directory name of the file
const path = require('path');
let dirname = path.dirname('./middleware/login.js');
console.log(dirname);
//Output - ./middleware
format()
format() method helps to format the path object into a string and returns the result.
const path = require('path');
let pathObj = { dir: './middleware', base: 'login.js' }
let pathResult = path.format(pathObj);
console.log(pathResult);
//Output - ./middleware/login.js
normalize()
Normalize the path and handles '..' and '.' in the path
const path = require('path');
let fixPath = path.normalize('Saheb/Tutorial/../json');
console.log(fixPath);
//Output - Saheb/json
Learn the module system in nodejs
I hope this article is helpful for you , i am very glad to help you thanks for reading