Usually, we have operations to handle file paths and filenames, such as getting the path pointing to the directory, getting the file name in the path, getting the file’s extension, etc.
NodeJS has provided us with the Path module to handle these operations.
Path Module in Node.js is used to manipulate the path of files.
To include the path module, we use the require() method:
const path = require("path");
Here are some supported methods in the Path module.
We can use the path.basename() function to get the file name. It has two uses as follows:
console.log(path.basename("public/image/cat.png")); // cat.png
console.log(path.basename("public/image/cat.png", ".png")); // cat
Example: We check the current file name
// Base file name
console.log(path.basename(__filename)); // hello.js
path.dirname() helps get the path to the file’s folder.
Example:
console.log(path.dirname(__filename));
// Result(Current directory): /home/user/dir
console.log(path.dirname("/public/image/logo.png"));
// Result: /public/image
Get the file extension value, but there are some special cases.
console.log(path.extname(__filename)); // .js
console.log(path.extname("cat.html")); // .html
console.log(path.extname("cat.md")); // .md
console.log(path.extname("cat.")); // .
console.log(path.extname("cat")); // (blank)
console.log(path.extname(".cat")); // (blank)
This function will return a path with an Object as a value. This object has five elements, including:
Case 1: If dir and base are provided, the result will be dir + base.
console.log(
path.format({
dir: "/home/user/dir",
base: "path.js",
})
);
// /home/user/dir/path.js
Case 2: root will be used if dir is not available
console.log(
path.format({
root: "/",
base: "path.js",
})
);
// /path.js
Case 3: name + ext is used if there is no base
console.log(
path.format({
dir: "/",
name: "path",
ext: ".js",
})
);
// /path.js
Case 4: If dir and root are used, they will be combined.
console.log(
path.format({
root: "/",
dir: "/home/user/dir",
base: "path.js",
ext: ".js",
name: "path",
})
);
// /home/user/dir/path.js
Case 5: If only base is available, it will return base.
console.log(
path.format({
base: "path.js",
})
);
// path.js
This function is opposite to the path.format function.
Example: Log current path object
// Create path object
console.log(path.parse(__filename));
/*
{
root: '/',
dir: '/home/user/dir',
base: 'path.js',
ext: '.js',
name: 'path'
}
*/
To concatenate paths, we use path.join().
console.log(path.join(__dirname, "test", "hello.html"));
// /home/user/dir/test/hello.html
path.isAbsolute() checks whether the path is an absolute path.
console.log(path.isAbsolute("/foo/bar")); // true
console.log(path.isAbsolute("/baz/..")); // true
console.log(path.isAbsolute("hello/")); // false
console.log(path.isAbsolute(".")); // false
We use path.sep to separate path.
console.log("foo/bar/baz".split(path.sep)); // [ 'foo', 'bar', 'baz' ]