Courses / Node.js: From First Script to Production / Chapter 6
Module 4 · Core modules and a basic web server · Chapter 6 of 27
Core Modules: Files, Paths, Buffers, Crypto and util
Builds on Globals and Modules: process, CommonJS and ES Modules and Asynchronous Programming: Callbacks, Promises and async/await. Next up: Building a Basic Web Server with node:http.
Part 1 · Paths and URLs
Why paths need a module
A college fest site stores poster images in folders, and the code that finds them must work on a Windows PC and a Linux server. Node gives you the node:path module for that, and the URL class for addresses on the web.
A path is text that names a file or folder. It looks simple until you meet two problems. Windows separates folders with a backslash (\) and Linux uses a forward slash (/). And a relative path such as data/marks.csv means different files depending on where the program was started. If you glue strings together by hand, you will get one of these wrong sooner or later.
node:path is pure text work. It never reads the disk, so calling it on a folder that does not exist is fine. It builds, cleans and takes apart path strings using the rules of the operating system you are on.
| Function | What it does |
|---|---|
path.join(a, b, ...) | Joins the pieces with the right separator, then cleans up . and ... |