Path
When developing programs in Node.js, we often need to manipulate paths in order to read or write files. This can be done with the path module.
While parts of paths can be accessed with individual methods like basename, using parse is simpler as it handles everything at once. With join, meanwhile, we combine a directory with a filename.
This Node.js program uses paths in a variety of ways with the Node path module. We have a require statement at the top to allow us to access this module.
parse()
on a string
that represents a path. The resulting object has properties for all the parts of the path.const path = require("node:path"); // Part 1: call parse on the path string. const value = "/home/sam/programs/program.js"; var result = path.parse(value); // Part 2: access properties on result of parse. console.log("Root:", result.root); console.log("Directory:", result.dir); console.log("Base:", result.base); console.log("Extension:", result.ext); console.log("Name:", result.name); // Part 3: use basename instead of parse to get base. var basename = path.basename(value); console.log("Base:", basename); // Part 4: access platform-specific path separator. var separator = path.sep; console.log("Sep:", separator); // Part 5: use join to merge a directory and a file name together. var part1 = "/home/sam"; var part2 = "temp.txt"; var joined = path.join(part1, part2); console.log("Join:", joined);Root: / Directory: /home/sam/programs Base: program.js Extension: .js Name: program Base: program.js Sep: \ Join: \home\sam\temp.txt
Manipulating paths can be done with strings alone, but using the path module makes it easier—and with path, we can even write platform-independent code that works reliably.