Path (module)
The Node.js path module provides useful methods for working with file paths. Two commonly used methods are path.join() and path.resolve().
Path.join()
The path.join() method in Node.js is used to join multiple path segments into a single normalized path. It takes multiple path segments as arguments and returns the concatenated path.
1 | const path = require('path'); |
The output of the above code will be
1 | folder/subfolder/file.txt |
The path.join() method concatenates the path segments based on passed arguments.
Path.resolve()
The path.resolve() method in Node.js is used to resolve a sequence of path segments into an absolute path. It takes one or more path segments as arguments and returns the resolved absolute path.
1 | const path = require('path'); |
Depending on the current working directory, the output of the above code will be an absolute path like –
1 | /hp/pc/folder/subfolder/file.txt |
Conclusion
Both path.join() and path.resolve() are powerful methods for working with file paths in Node.js. path.join() helps in concatenating path segments into a single path, while path.resolve() resolves a sequence of path segments into an absolute path.