Understanding Node.js Path Module
- Node.js
- JavaScript
- Backend Development
The path module in Node.js provides utilities for working with file and directory paths. It's a core module, meaning it comes pre-installed with Node.js, so there's no need to install it separately.
Why Use the path Module?
- Cross-Platform Compatibility: File paths differ between operating systems (/ on Unix-like vs \ on Windows). The path module ensures your code works seamlessly across platforms.
- Simplifies Path Operations: Tasks like joining, resolving, or normalizing paths become straightforward.
- Error Prevention: Avoid hardcoding paths, reducing potential errors and improving maintainability.
importing path module
const path = require('path'); // CommonJS
// or in ES modules
import path from 'path';
```js
const path = require('path'); // CommonJS
import path from 'path'; //// ES modules
Code snippets for path modules
//1.path.basename()
const filePath = '/users/sudarshan/docs/file.txt';
console.log(path.basename(filePath)); // Output: file.txt
console.log(path.basename(filePath, '.txt')); // Output: file
//2.path.dirname()
console.log(path.dirname(filePath)); // Output: /users/sudarshan/docs
//3.path.extname()
console.log(path.extname(filePath)); // Output: .txt
//4.path.join()
const folder = '/users/sudarshan';
const file = 'file.txt';
console.log(path.join(folder, 'docs', file));
// Output: /users/sudarshan/docs/file.txt
path.resolve() and path.normalize()
path.resolve()
- Resolves a sequence of path segments into an absolute path.
- Takes the current working directory into account.
path.normalize() - Normalizes a path by resolving .. and . segments.
console.log(path.resolve('docs', 'file.txt'));
// Output: Absolute path based on your current directory.hint:cwd()+docs+file.txt
console.log(path.normalize('/users/sudarshan/../docs/file.txt'));
// Output: /users/docs/file.txt
Note:What is absolute and relative path?
Absolute path start from root while relative path depend on current working directory.
Absolute path start from / or \ and relative path start from nothing but direct dir or file name.
We can also find relative path from two path.eg:
const from = '/users/sudarshan/docs';
const to = '/users/sudarshan/images';
console.log(path.relative(from, to));
// Output: ../images