Modules, npm and the Debugger

Real Node programs are many files and many packages. Split a program into modules, meet Node's built-in modules and the older require you'll still see, describe a project in package.json, install packages and pin their versions, and pause a program in VS Code's debugger to see what it's really doing.

Updated

Modules in Node.js

  1. Modules: import and export (Apprentice): A module is a file that shares only what it exports; another file imports it by name (a named export) or under a name it picks (the default export), and a package.json in Node or type="module" on a page makes it run.
  2. Node's Built-In Modules, and the require You'll Still See (Apprentice): Node comes with built-in modules for files, file names, the computer and everyday helpers, imported with node in front of their names, and older code shares modules with require and module.exports, which you can read and rewrite as import and export.

npm and package.json

  1. npm and Packages (Journeyman): npm is an app store for code that comes with Node.js; you'll describe a project in package.json, install packages into node_modules, tell dependencies from devDependencies, and run the project's commands as npm scripts.
  2. Package Versions, npm ci and npm audit (Apprentice): A version range in package.json says which versions a project accepts, package-lock.json pins the exact ones installed, npm ci installs exactly those, and npm outdated, npm audit and npx check a project for updates, check it for security problems and run a package's command.

Debugging Node.js

  1. Debugging with Breakpoints (Apprentice): A debugger pauses your program at a breakpoint, lets you run it one line at a time, and shows every variable's value as you go, in VS Code for Node and in the browser's DevTools for a page, so you can see the line where a value goes wrong.

Exercise: Book Club Picks

  1. Exercise: Book Club Picks (Apprentice): Split the Chapter Two Book Club's one long planner file into three modules with named exports, add npm scripts, install date-fns at a pinned version to format the meeting date, and keep node_modules out of Git, with node --test checking every step.