Node.js path and os
ExampleNode.js
const path = require("path");
const os = require("os");
const p = path.join("/home/user", "docs", "..", "notes", "todo.md");
console.log(p);
console.log(path.dirname(p));
console.log(path.basename(p, ".md"));
console.log(path.parse("/a/b/c.txt"));
console.log(path.isAbsolute("/a"), path.isAbsolute("a"));
console.log(path.resolve("/a/b", "../c"));
console.log(typeof os.cpus().length, os.EOL === "\n");
console.log(typeof os.totalmem(), typeof os.hostname());Output
/home/user/notes/todo.md
/home/user/notes
todo
{ root: '/', dir: '/a/b', base: 'c.txt', ext: '.txt', name: 'c' }
true false
/a/c
number true
number stringAlways build paths with path.join instead of string concatenation so they work on Windows and Linux alike.
Quick check
Why use path.join instead of adding strings with /?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.