Nodejs Path Module
[Node.js Built-in Modules](#)
* * *
The `path` module in Node.js is a built-in core module, specifically designed for handling file and directory paths.
path provides a series of practical methods that allow you to safely and efficiently operate on file paths in different operating system environments.
### Why You Need the path Module
Different operating systems use different path separators:
* Windows uses backslash ``
* Unix/Linux/macOS uses forward slash `/`
The path module automatically handles these differences, making your code work across different platforms.
* * *
## Basic Usage of the path Module
### Importing the path Module
const path = require('path');
### Common Methods
#### 1. path.join([...paths]) - Join Paths
## Example
const fullPath = path.join('/user','documents','file.txt');
console.log(fullPath);
// Output on Unix: /user/documents/file.txt
// Output on Windows: userdocumentsfile.txt
#### 2. path.resolve([...paths]) - Resolve Absolute Path
## Example
const absolutePath = path.resolve('src','app.js');
console.log(absolutePath);
// Outputs the absolute path under the current working directory, e.g.: /home/user/project/src/app.js
#### 3. path.basename(path[, ext]) - Get File Name
## Example
console.log(path.basename('/user/docs/file.txt'));// file.txt
console.log(path.basename('/user/docs/file.txt','.txt'));// file
#### 4. path.dirname(path) - Get Directory Name
## Example
console.log(path.dirname('/user/docs/file.txt'));// /user/docs
#### 5. path.extname(path) - Get File Extension
## Example
console.log(path.extname('index.html'));// .html
console.log(path.extname('file'));// empty string
* * *
## Cross-Platform Path Handling
### Path Separators
* `path.sep` - Platform-specific path separator
console.log(path.sep); // Outputs '' on Windows, '/' on Unix
* `path.delimiter` - Platform-specific path separator (for PATH environment variable)
console.log(path.delimiter); // Outputs ';' on Windows, ':' on Unix
### Path Normalization
Using `path.normalize(path)` can normalize paths, handling excess `.`, `..` and separators:
## Example
console.log(path.normalize('/user//docs/../file.txt'));// /user/file.txt
* * *
## Path Parsing and Format Conversion
### path.parse(path) - Parse Path to Object
## Example
const pathObj = path.parse('/user/docs/file.txt');
console.log(pathObj);
/*
{
root: '/',
dir: '/user/docs',
base: 'file.txt',
ext: '.txt',
name: 'file'
}
*/
### path.format(pathObject) - Build Path from Object
## Example
const pathStr = path.format({
dir:'/user/docs',
name:'file',
ext:'.txt'
});
console.log(pathStr);// /user/docs/file.txt
* * *
## Practical Application Examples
### Example 1: Build Cross-Platform File Path
## Example
const configPath = path.join(__dirname,'config','settings.json');
console.log(configPath);
### Example 2: Handle User Uploaded Files
## Example
function saveUploadedFile(uploadDir, originalName){
const ext = path.extname(originalName);
const baseName = path.basename(originalName, ext);
const timestamp =Date.now();
const newFileName = `${baseName}_${timestamp}${ext}`;
return path.join(uploadDir, newFileName);
}
### Example 3: Check File Extension
## Example
function isImageFile(filename){
const ext = path.extname(filename).toLowerCase();
return['.jpg','.jpeg','.png','.gif'].includes(ext);
}
* * *
## Methods and Properties
The methods and properties of the path module are as follows:
| Method | Description | Example |
| --- | --- | --- |
| `path.basename(path[, ext])` | Returns the last part of the path (file name). Optional parameter `ext` is used to remove the file extension. | `path.basename('/foo/bar/baz.txt'); // Output: 'baz.txt'` |
| `path.dirname(path)` | Returns the directory part of the path. | `path.dirname('/foo/bar/baz.txt'); // Output: '/foo/bar'` |
| `path.extname(path)` | Returns the file extension in the path. | `path.extname('/foo/bar/baz.txt'); // Output: '.txt'` |
| `path.join([...paths])` | Joins multiple paths into one path, automatically handling path separators. | `path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); // Output: '/foo/bar/baz/asdf'` |
| `path.resolve([...paths])` | Resolves a sequence of paths to an absolute path, processing each path segment from right to left until an absolute path is constructed. | `path.resolve('/foo/bar', './baz'); // Output: '/foo/bar/baz'` |
| `path.normalize(path)` | Normalizes the path, removing redundant `.` and `..`, and replacing path separators according to the current operating system. | `path.normalize('/foo/bar//baz/asdf/quux/..'); // Output: '/foo/bar/baz/asdf'` |
| `path.isAbsolute(path)` | Checks if the path is an absolute path. | `path.isAbsolute('/foo/bar'); // Output: true` |
| `path.relative(from, to)` | Returns the relative path from `from` path to `to` path. | `path.relative('/foo/bar/baz', '/foo/bar/qux'); // Output: '../qux'` |
| `path.parse(path)` | Parses a path string into an object, containing `root`, `dir`, `base`, `ext` and `name` properties. | `path.parse('/home/user/dir/file.txt');` Output: `{ root: '/', dir: '/home/user/dir', base: 'file.txt', ...}` |
| `path.format(pathObject)` | Formats a path object into a path string, the opposite of `path.parse`. | `path.format({ root: '/', dir: '/home/user/dir', base: 'file.txt' }); // Output: '/home/user/dir/file.txt'` |
| `path.sep` | Provides the path separator for the current operating system (POSIX is `'/'`, Windows is `''`). | `console.log(path.sep); // Output: '' (Windows) or '/' (POSIX)` |
| `path.delimiter` | Provides the path separator (separator for paths in environment variables), POSIX is `:`, Windows is `;`. | `console.log(path.delimiter); // Output: ';' (Windows) or ':' (POSIX)` |
### Example
Create a main.js file with the following code:
## Example
const path = require('path');
// Get file name
console.log('File name:', path.basename('/foo/bar/baz.txt'));// Output: 'baz.txt'
// Get directory name
console.log('Directory name:', path.dirname('/foo/bar/baz.txt'));// Output: '/foo/bar'
// Get file extension
console.log('Extension:', path.extname('/foo/bar/baz.txt'));// Output: '.txt'
// Join paths
console.log('Joined path:', path.join('/foo','bar','baz/asdf','quux','..'));// Output: '/foo/bar/baz/asdf'
// Resolve absolute path
console.log('Absolute path:', path.resolve('/foo/bar','./baz'));// Output: '/foo/bar/baz'
// Normalize path
console.log('Normalized path:', path.normalize('/foo/bar//baz/asdf/quux/..'));// Output: '/foo/bar/baz/asdf'
// Check if absolute path
console.log('Is absolute path:', path.isAbsolute('/foo/bar
YouTip