path Examples
This page was last reviewed on Dec 26, 2023.
Dot Net Perls
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.
Example. 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.
Part 1 We call parse() on a string that represents a path. The resulting object has properties for all the parts of the path.
Part 2 We access the properties on the object returned by parse. The root, dir, base, ext and name are shown.
Part 3 It is possible to use methods in the path module like basename instead of properties (like name) returned by parse.
Part 4 On Windows, we have a backslash character as the path separator, but macOS and Linux use a forward slash.
Part 5 With join, we can merge together a directory and a file name without worrying about exactly what separator needs to be placed between them.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 26, 2023 (new).
© 2007-2024 Sam Allen.