Working with Paths
The path module works with file paths. A path is the address of a file or folder.
Joining a path
This joins notes and hello.txt into one path.
const path = require("path");
console.log(path.join("notes", "hello.txt"));The folder of a path
This gives back the folder part of the path.
console.log(path.dirname("notes/hello.txt"));The ending of a file
This gives back the extension of hello.txt.
console.log(path.extname("hello.txt"));Example
const path = require("path");
const full = path.join("notes", "hello.txt");
console.log(full);
console.log(path.basename(full));
console.log(path.extname(full));Key points
- Use require("path") to load the path module.
- path.join joins folder names into one path.
- path.join uses the slash of the machine it runs on.
- An extension is the ending of a file name, like .txt.
- path.basename gives back the file name from a path.
- path.extname gives back the extension of a file name.
- path.dirname gives back the folder of a path.
In this example, path.join makes the path notes/hello.txt. The first print shows the whole path. The second print shows the file name, hello.txt. The last print shows the extension, .txt.
Note
Paths typed by hand can break on another machine.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which method joins folder names into one path?