Node.js path Module
Node.js's path The module is a built-in core module dedicated to handling file and directory paths.
path provides a series of utility methods that let you manipulate file paths safely and efficiently across different operating system environments.
Why you need the path module
Different operating systems use different path separators:
- Windows uses a backslash
\ - Unix/Linux/macOS uses a forward slash
/
path The module automatically handles these differences, allowing your code to work properly on different platforms.
Basic usage of the path module
Importing the path module
const
path
=
require
(
'path'
)
;
// 2022-01-01 00:00:00 GMT
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: \user\documents\file.txt
2. path.resolve([...paths]) - Resolve to an absolute path
Example
const
absolutePath
=
path.
resolve
(
'src'
,
'app.js'
)
;
console.
log
(
absolutePath
)
;
// Output the absolute path under the current working directory, e.g.: /home/user/project/src/app.js
3. path.basename(path[, ext]) - Get the filename
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 the directory name
Example
console.
log
(
path.
dirname
(
'/user/docs/file.txt'
)
)
;
// /user/docs
5. path.extname(path) - Get the extension
Example
console.
log
(
path.
extname
(
'index.html'
)
)
;
// .html
console.
log
(
path.
extname
(
'file'
)
)
;
// Empty string
Cross-platform path handling
Path separator
-
path.sep- Platform-specific path separator
console.log(path.sep); // Windows outputs '', Unix outputs '/'
-
path.delimiter- Platform-specific path separator (used in the PATH environment variable)
console.log(path.delimiter); // Windows outputs ';', Unix outputs ':'
Path normalization
Use path.normalize(path) can normalize paths, handling redundant .、.. and separators:
Example
console.
log
(
path.
normalize
(
'/user//docs/../file.txt'
)
)
;
// /user/file.txt
Path parsing and format conversion
path.parse(path) - Parse a path into an 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 a path from an 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 a 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 a 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 listed in the table below:
| Method | Description | Example |
|---|---|---|
path.basename(path[, ext]) |
Returns the last portion of a path (the filename). The optional parameter ext is used to remove the file extension. |
path.basename('/foo/bar/baz.txt'); // 输出: 'baz.txt' |
path.dirname(path) |
Returns the directory portion of a path. | path.dirname('/foo/bar/baz.txt'); // 输出: '/foo/bar' |
path.extname(path) |
Returns the extension of the file in a path. | path.extname('/foo/bar/baz.txt'); // 输出: '.txt' |
path.join([...paths]) |
Joins multiple paths into one path, automatically handling path separators. | path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); // 输出: '/foo/bar/baz/asdf' |
path.resolve([...paths]) |
Resolves a sequence of paths into an absolute path, processing each path segment from right to left until an absolute path is constructed. | path.resolve('/foo/bar', './baz'); // 输出: '/foo/bar/baz' |
path.normalize(path) |
Normalizes a path, removing redundant . and ..and replacing path separators according to the current operating system. |
path.normalize('/foo/bar//baz/asdf/quux/..'); // 输出: '/foo/bar/baz/asdf' |
path.isAbsolute(path) |
Checks whether a path is absolute. | path.isAbsolute('/foo/bar'); // 输出: true |
path.relative(from, to) |
Returns the relative path from from path to to path. |
path.relative('/foo/bar/baz', '/foo/bar/qux'); // 输出: '../qux' |
path.parse(path) |
Parses a path string into an object containing root、dir、base、ext and name attribute. |
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 reverse of path.parse opposite. |
path.format({ root: '/', dir: '/home/user/dir', base: 'file.txt' }); // 输出: '/home/user/dir/file.txt' |
path.sep |
Provides the path separator for the current operating system (POSIX is '/', on Windows it is '\')。 |
console.log(path.sep); // 输出: '\' (Windows) 或 '/' (POSIX) |
path.delimiter |
Provides the path delimiter (the separator for paths in environment variables), POSIX is :, on Windows it is ;。 |
console.log(path.delimiter); // 输出: ';' (Windows) 或 ':' (POSIX) |
Example
Create a main.js file with the following code:
Example
const
path
=
require
(
'path'
)
;
// Get the filename
console.
log
(
'Filename:'
,
path.
basename
(
'/foo/bar/baz.txt'
)
)
;
// Output: 'baz.txt'
// Get the directory name
console.
log
(
'Directory name:'
,
path.
dirname
(
'/foo/bar/baz.txt'
)
)
;
// Output: '/foo/bar'
// Get the 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 the absolute path
console.
log
(
'Absolute path:'
,
path.
resolve
(
'/foo/bar'
,
'./baz'
)
)
;
// Output: '/foo/bar/baz'
// Normalize the path
console.
log
(
'Normalized path:'
,
path.
normalize
(
'/foo/bar//baz/asdf/quux/..'
)
)
;
// Output: '/foo/bar/baz/asdf'
// Check whether it is an absolute path
console.
log
(
'Is absolute path:'
,
path.
isAbsolute
(
'/foo/bar'
)
)
;
// Output: true
// Relative path
console.
log
(
'Relative path:'
,
path.
relative
(
'/foo/bar/baz'
,
'/foo/bar/qux'
)
)
;
// Output: '../qux'
// Parse the path into an object
const
parsedPath
=
path.
parse
(
'/home/user/dir/file.txt'
)
;
console.
log
(
'Parsed path object:'
,
parsedPath
)
;
// Output: { root: '/', dir: '/home/user/dir', base: 'file.txt', ext: '.txt', name: 'file' }
// Format the object into a path
const
formattedPath
=
path.
format
(
parsedPath
)
;
console.
log
(
'Formatted path:'
,
formattedPath
)
;
// Output: '/home/user/dir/file.txt'
Node.js Built-in Modules