Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
Every file in the system has a path.
On Linux and macOS, a path might look like:
/users/flavio/file.txt
while Windows computers are different, and have a structure such as:
C:\users\flavio\file.txt
You need to pay attention when using paths in your applications, as this difference must be taken into account.
Include the module in your code with
const path = require('path')
and you can start using its methods.
Getting information out of a path
Given a path, you can extract information out of it using those methods:
dirname: get the parent folder of a filebasename: get the filename partextname: get the file extension
Example:
const notes = '/users/flavio/notes.txt'
path.dirname(notes) // /users/flavio
path.basename(notes) // notes.txt
path.extname(notes) // .txt
You can get the file name without the extension by specifying a second argument to basename:
path.basename(notes, path.extname(notes)) // notes
Working with paths
You can join two or more parts of a path by using path.join():
const name = 'flavio'
path.join('/', 'users', name, 'notes.txt') //'/users/flavio/notes.txt'
You can get the absolute path calculation of a relative path using path.resolve():
path.resolve('flavio.txt') //'/Users/flavio/flavio.txt' if run from my home folder
Node appends the path to the current working directory. If you pass a second argument, resolve uses the first as the base for the second:
path.resolve('tmp', 'flavio.txt') // '/Users/flavio/tmp/flavio.txt' if run from my home folder
If the first parameter starts with a slash, that means it’s an absolute path:
path.resolve('/etc', 'flavio.txt') // '/etc/flavio.txt'
path.normalize() is another useful function; it resolves the actual path when the string contains relative segments like . or .., or duplicate slashes:
path.normalize('/users/flavio/..//test.txt') // '/users/test.txt'
Neither resolve nor normalize checks whether the path exists. They only compute a path from the given segments.