The path.join()
method in Node.js Path module is used to join all given path segments together to form a single well formed
path. While forming the path path.join() method takes care of the following.
- Uses the platform-specific separator as a delimiter. For example / on POSIX and either \ or / on Windows.
- Normalizes the resulting path. While normalizing following tasks are done.
- Resolves '..' (parent directory or one level up) and '.' (current directory) segments.
- When multiple, sequential path segment separation characters are found (e.g. / on POSIX and either \ or / on Windows), they are replaced by a single instance of the platform-specific path segment separator (/ on POSIX and \ on Windows).
- If the path is a zero-length string, '.' is returned, representing the current working directory.
path.join() method syntax
path.join([...paths])
...paths is a sequence of path segments of type string which are joined together to form a path.
Method returns a String representing the final path.
Throws TypeError if any of the path segments is not a string.
path.join() method Node.js examples
1. Joining various path segments
const path = require('path'); const filePath = path.join("app", "views", "mypage.html"); console.log(filePath);
Output
app/views/mypage.html
2. Normalizing path by removing any extra path separators.
const path = require('path'); const filePath = path.join("app", "/views", "//mypage.html"); console.log(filePath);
Output
app/views/mypage.html
3. Using with __dirname to get the path starting from the directory of currently executing file.
const path = require('path'); const filePath = path.join(__dirname, "views", "mypage.html"); console.log(filePath);
Output
D:\NETJS\NodeJS\nodews\views\mypage.html
Same code in Linux system
const path = require('path'); const filePath = path.join(__dirname, "views", "mypage.html"); console.log(filePath);
Output
/home/netjs/nodeapp/views/mypage.html
4. Using '..' path segment to go one level up. For example, if file is executing in directory D:\NETJS\NodeJS\nodews\views\mypage.html then the following code
const path = require('path'); const filePath = path.join(__dirname, "..", "views", "mypage.html"); console.log(filePath);gives the output as
D:\NETJS\NodeJS\views\mypage.html
It is because the file where this code resides is in D:\NETJS\NodeJS\nodews and '..' path segment means going one level up meaning D:\NETJS\NodeJS
That's all for this topic Node.js path.join() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Angular Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment