How to use the path module in Node.js?
In Node.js, the path module provides utilities for working with files and directories path. It's a built-in module in Node.js, so we don't need to install anything to use it.
This module is particularly useful when working with file systems that have different file separators such as Windows and Linux.
In Linux, "/"
is used in file paths, and in Windows "\"
is used.
Linux: "/home/document/file.txt"
Windows: "C:\user\document\file.txt"
This module handles path separation and other platform-specific details automatically. It provides many useful methods to manipulate files and directories paths.
In this blog, we will discuss various methods of this module with examples.
Let's dive in!
path.basename( path[, ext] )
This method returns the last portion of a file path. The optional ext argument can be used to remove the file extension.
// import path module
const path = rquire("path");
const fileName = path.basename('/path/to/file.txt');
// Output: file.txt
const fileNameWithoutExt = path.basename('/path/to/file.txt', '.txt');
// Output: file
path.dirname(path)
This method returns the directory name of the provided file path.
const directory = path.dirname('/home/document/file.txt');
// Output: /home/document
path.normalize(path)
It is used to normalise a given file or directory path. It removes redundant slashes and dots from a path.
here is how it works:
Replace consecutive slashes with a single slash.
Resolves parent(..) and the current directory(.) references appropriately.
This method is useful when a file path is obtained from a different source like user input or configuration file. It makes sure that the resulting path is consistent and safe to use.
//Import
const path = require('path');
// Replace consecutive slashes
const x = path.normalize("/home/user//file.txt");
console.log(x); //Output: /home/user/file.txt
// Resolve parent reference
const p = path.normalize("/home/user/../file.txt");
console.log(p); //Output: /home/file.txt
const s = path.normalize("/home/../user/dir/.././file.txt");
console.log(s); //Output:/user/file.txt
path.join([...paths])
This method joins all the given path segments together with a platform-specific separator[Linux — "/" window — "\"] and then performs normalization on the resulting path.
const path = require('path')
const filePath = path.join('/home', 'user', "/..", 'file.txt');
// Output: /home/file.txt
path.delimiter
The path.delimiter
property is a platform-specific string that is used to separate individual directories in the PATH environmental variable.
On Windows, the path.delimiter
is ;
On Linux, the path.delimiter
is :
//import path module
const path = require('path')
// On Linux
console.log(path.delimiter);
// :
console.log(process.env.PATH);
//'/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
// On Window
console.log(path.delimiter);
// ;
console.log(process.env.PATH);
// 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'
path.relative(fromPath, toPath)
This method is used to determine the relative path from a provided path (fromPath) to another (toPath).
It calculates the relative path by considering the given path as current working directory.
const path = require('path');
const fromPath = '/home/user/projects/myApp';
const toPath = '/home/user/documents/file.txt';
const relativePath = path.relative(fromPath, toPath);
console.log(relativePath);
// ../../documents/file.txt
path.resolve([...paths])
This method resolves a sequence of path segments to an absolute path.
It starts processing path segments from the right to the left and prepends path segments until it finds a segment starting with a forward slash "/"
on Linux and "\"
on Windows.
If there is no path segment starting with "/" (on Linux) or "\" (on Windows), then the current working directory is used to make an absolute path.
const path = require('path');
path.resolve('/foo/bar', '/tmp/file/');
// Returns: '/tmp/file'
path.resolve('/home/user', '/projects', 'myApp');
// Return: /projects/myApp
path.resolve('myApp', 'src', 'index.js');
// Return: /current/working/directory/myApp/src/index.js
path.resolve('/home/usr', '../projects', 'myApp');
// Return: /home/projects/myApp
path.dirname(path)
This method returns the directory name of the given path.
const path = require('path');
path.dirname('/home/documents/file.txt');
// Returns: /home/documents
path.dirname("/home/user/projects/myApp");
// Returns: /home/user/projects
path.extname(path)
This method is used to get the file extension name from the file path. It returns a string after last .
(dot) in the file path. If there is no .
, then it returns an empty string.
const path = require("path");
path.extname('index.html');
// Returns: '.html'
path.extname('index.coffee.md');
// Returns: '.md'
path.extname('index.');
// Returns: '.'
path.extname('index');
// Returns: ''
path.extname('.index');
// Returns: ''
path.format(pathObject)
This method is used to format an object into a file path string.
It takes an object containing individual components of a file path such as the root, base, directory, file name, and extension.
The object has the following properties:
root: root name
dir: file directory
base: file name with extension
name: only file name
ext: file extension, including the dot(.)
The object properties have priorities over one another. All the properties are not used to build a path, only a group of properties are used to build a path. Such as:
The root is ignored if dir, root and base are provided.
root will be used if dir is not provided
name and ext will be used if base is not provided.
// If `dir`, `root` and `base` are provided, `root` is ignored.
path.format({
root: '/',
dir: '/home/user/dir',
base: 'file.txt',
});
// Return: '/home/user/dir/file.txt'
// `root` will be used if `dir` is not specified.
// If only `root` is provided or `dir` is equal to `root` then the
// platform separator will not be included. `ext` will be ignored.
path.format({
root: '/',
base: 'file.txt',
ext: 'ignored',
});
// Returns: '/file.txt'
// `name` + `ext` will be used if `base` is not specified.
path.format({
root: '/',
name: 'file',
ext: '.txt',
});
// Returns: '/file.txt'
// The dot will be added if it is not specified in `ext`.
path.format({
root: '/',
name: 'file',
ext: 'txt',
});
// Returns: '/file.txt'
path.parse(path)
This method is used to parse a file path into an object that contains its individual component such as the root, directory, file name, extension and base name.
This method is the opposite of the path.format()
method.
const path = require('path');
const filePath = '/home/user/documents/file.txt';
const pathObject = path.parse(filePath);
console.log(pathObject);
/*{
"root": "/",
"dir": "/home/user/documents",
"base": "file.txt",
"ext": ".txt",
"name": "file"
} */
Conclusion
In Node.js, the path module helps us to manipulate file paths and directories without worrying about system environments(file systems) such as Linux or Windows.
We have discussed methods that are present in this module such as:
basename(): Return the last part of a path.
normalize(): Remove redundant slashes and dots.
join(): Join path segments together.
format(): Convert an object to a file path.
parse(): Convert file path to an object.
relative(): Return the relative path of the target path from a given path.
resolve(): Return absolute path from a sequence of path segments.
References
Subscribe to my newsletter
Read articles from Ajay directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by