Node.js Path Module is a built-in module, it comes with Node.js itself to work with file paths. It enables developers to create file paths independent of the platform that help to create cross-platform applications.
The Path module in Node.js is only responsible for working with file paths, such as manipulating, creating, and joining file paths. It doesn’t provide the functionality to create or read files directly, for that there is another module File System that provides many methods for interacting with files and directories. Path module just provides different methods and properties to get the indifferent format depending upon the requirements such as methods to convert relative paths to absolute, resolve and normalize paths, extract path components, and join paths.
In this tutorial, we will learn about all these methods and properties which eventually help you to perform file interaction more easily by getting desired file path.
Importing Node.js Path Module
Node.js Path is a built-in module, no need to install it manually, you can just import it in a JavaScript file where you want to use its methods and properties.
Syntax:
Below is the syntax for importing the Path module.
const path = require('path');
Here we have used a constant variable as we are not going to change its value. We will use this variable throughout this document to keep things simple.
Node.js Path Properties and Methods with Examples
The Path module comes with multiple properties and methods to let developers easily work with file paths.
Note: The arguments surrounded by [ ] (square brackets) mean they are optional. You may pass them depending on requirements.
1. basename(path, [ext])
Returns the last part of a file path. A second parameter will hold the extension of the file.
Example:
path.basename('/random/random') //random
path.basename('/random/random.txt') //random.txt
path.basename('/random/random.txt', '.txt') //random
2. delimiter
Returns the delimiter for the path. Windows uses the ‘;’ (semicolon) delimiter and Linux and MacOS support the ‘:’ (colon) delimiter.
Example:
path.delimiter // :
3. dirname(path)
Returns the directories of a path. This is the most frequently used method while developing an application having File interactions.
Example:
path.dirname('/random/something') // /random
path.dirname('/random/something/file.txt') // /random/something
4. extname(path)
Returns the file extension of a path.
Example:
path.extname('/random/test') // ''
path.extname('/random/test/file.txt') // '.txt'
5. format(pathObject)
Returns path string from a path object. It is the opposite of path.parse(). It accepts keys or properties.
Example:
path.format({ dir: '/Users/Cassandra', base: 'file.txt' }) // '/Users/Cassandra/file.txt'
path.format({ root: '/Users/Cassandra', name: 'file', ext: 'txt' }) // '/Users/Cassandra/file.txt' // WINDOWS
path.format({ dir: 'C:\\Users\\Cassandra', base: 'file.txt' }) // 'C:\\Users\\Cassandra\\file.txt'
Note: The root key is ignored in case dir is present, and ext and name keys are ignored if the base is provided.
6. isAbsolute(path)
Checks if a file is an absolute path or not. Returns true if it is, otherwise, false.
Example:
path.isAbsolute('/random/test') // true
path.isAbsolute('./random/test') // false
7. join([…paths])
Join a number of path segments into one.
Example:
const name = 'Cassandra'
path.join('/', 'Users', name, 'test.txt') //'/Users/Cassandra/test.txt'
8. normalize(path)
This method performs normalization to estimate the actual path when relative specifiers like ‘.’ or ‘..’, double slashes are present.
Example:
path.normalize('/Users/Cassandra/..//list.txt') //'/Users/list.txt'
9. parse(path)
Formats the path string into a path object with the properties that it comprises:
- root: the root of the path
- dir: the directory path starting from the root
- base: the file name and extension
- name: the file name
- ext: the extension of the path
We are required to pass the path string:
Example:
path.parse('/Users/list.txt')
Output:
{ root: '/', dir: '/Users', base: 'list.txt', ext: '.txt', name: 'list' }
10. posix
Returns an object that contains POSIX-specific properties and functions. This property enables users to access POSIX-specific implementations of the path functions.
Example:
path.posix
11. relative(from, to)
Returns a relative path from the first path to the second, based on the current working directory.
Example:
path.relative('/Users/Cassandra', '/Users/Cassandra/test.txt') //'test.txt'
path.relative('/Users/Cassandra ', '/Users/Cassandra/something/test.txt') //'something/test.txt'
12. resolve([…paths])
Resolve a relative path into an absolute path.
Example:
path.resolve('list.txt') //'/Users/Cassandra/list.txt'
13. sep
Returns the platform-specific segment separator of the path.
- ‘\’ on Windows
- ‘/’ on POSIX
Example:
path.sep // /
14. win32
Returns an object that contains Windows-specific properties and functions. This property enables users to access Windows-specific implementations of the path functions.
Example:
path.win32
Working with File Paths
Let’s look at a more thorough instance of how the Path module works with paths, we’ll also use the File System module to see its coordination with the Path module.
Example:
const path = require('path'); // import path
const fs = require('fs'); // import filesystem
const fileName = 'example.txt'; // file name
const filePath = path.join(__dirname, fileName); // use join method to join the current path with the file name
fs.writeFile(filePath, 'Hello, World!', (err) => { // use writeFile method to write the file in the correct path
if (err) throw err;
});
console.log(path.resolve('example.txt')) // use resolve method to get the absolute path of the file
Here we have first imported both the Path & File System module, then defined a name for a txt file that we want to create, then used the Path module function join() to join the correct working directory and the file we want to create so that the file is created in the current working folder, then used writeFile() function to write on the specified path with a callback for handling errors, and finally to verify the resulting path we have to use another Path module function resolve().
Output:
/home/runner/example/example.txt
See, how useful the Path module is, we successfully created the file in the desired folder.
Conclusion
Node has a module File System, popularly known as FS module to interact with files but to interact with files we need to get the exact file path. Here comes the Path module. The Path module is used to get the desired file path. It provides various methods and properties for performing different operations on file paths, which we discussed in this tutorial. Hope you got enough knowledge after reading it.
Read More: How to Check if a File Exists in Node.js
Reference
https://nodejs.org/api/path.html