Node.js and npm basics

15 min read javascript
Course contents (16 lessons)
  1. Modern syntax
  2. Destructuring, spread and rest
  3. ES modules: import and export
  4. Objects, this and errors
  5. Classes and prototypes
  6. Understanding this in JavaScript
  7. Error handling: try, catch and custom errors
  8. Asynchronous JavaScript
  9. The event loop: how JavaScript handles waiting
  10. From callbacks to promises to async/await
  11. Fetch and REST APIs
  12. Working in the browser
  13. Local storage and session storage
  14. Debugging with browser DevTools
  15. Performance basics: debounce and throttle
  16. Node.js essentials
  17. Node.js and npm basics
  18. Working with files in Node.js
  19. A tiny HTTP server with Node.js
  20. Testing and the final project
  21. Testing basics with the Node.js test runner
  22. Final project: a post explorer with modules and fetch

What Node.js adds

In the browser, JavaScript works with pages. In Node.js, it works with your computer: files, networks, processes. Node is used for command-line tools, build tools, scripts and web servers. It runs the same V8 engine as Chrome.

Check that you have it, and use a current LTS version:

node --version
npm --version

npm comes with Node. It is the package manager, a tool for downloading and managing other people's code, and also for running your project scripts.

Starting a project

Create a folder and run:

npm init -y

This writes a package.json file. It describes your project. Open it and you will see something like this:

{
  "name": "my-tool",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "node index.js"
  }
}

Add "type": "module" by hand so you can use import and export as in the modules lesson. The scripts section holds shortcuts you run with npm run.

Installing packages

To use a package from the npm registry, install it:

npm install dayjs

This does three things. It downloads the package into the node_modules folder, adds it to dependencies in package.json, and records the exact version in package-lock.json. Then you import it:

import dayjs from "dayjs";
console.log(dayjs().format("YYYY-MM-DD"));

Some packages are only needed while developing, such as test tools and formatters. Install them with --save-dev (or -D), and they go under devDependencies:

npm install -D prettier

To remove one, use npm uninstall dayjs.

Things I always do

  • **Commit package.json and package-lock.json.** The lock file makes sure your teammates and your server install the same versions.
  • **Never commit node_modules.** Add it to .gitignore. Anyone can recreate it with npm install.
  • **Run npm ci on servers and in CI.** It installs exactly what the lock file says and fails if it does not match.
  • Install fewer packages. Every dependency is code you did not write and must trust. Before adding a package for something small, check whether Node or the browser already does it.

Version numbers

Versions look like 4.17.21, meaning major, minor and patch. In package.json you will see ^4.17.21. The caret allows updates of minor and patch versions but not a new major version, since major versions may break things. The command npm outdated lists packages with newer versions.

npm scripts

Scripts give your project a common set of commands:

"scripts": {
  "start": "node index.js",
  "dev": "node --watch index.js",
  "test": "node --test",
  "format": "prettier --write ."
}

Run them with npm run dev. The names start and test are special, so you can write npm start and npm test. The flag --watch restarts Node whenever a file changes, which is convenient during development.

npx

npx runs a package without installing it permanently, for example npx serve . serves the current folder over HTTP. It is a good way to try a tool once.

A tiny command-line tool

Node gives you the command-line arguments in process.argv. The first two entries are the path of Node and the path of your script, so your own arguments start at index 2.

// greet.js
const args = process.argv.slice(2);
const name = args[0] ?? "friend";
const shout = args.includes("--shout");

let message = `Hello, ${name}!`;
if (shout) message = message.toUpperCase();

console.log(message);
console.log("Node version:", process.version);
console.log("Running in:", process.cwd());

Run node greet.js Sara --shout and you get HELLO, SARA!. Run it with no arguments and you get Hello, friend!. For tools with many options, the built-in util.parseArgs function can parse flags for you.

Environment variables

Settings that change between your laptop and the server, such as a port number or an API key, belong in environment variables. Read them from process.env:

const port = Number(process.env.PORT) || 3000;
const mode = process.env.NODE_ENV ?? "development";
console.log(`Port ${port}, mode ${mode}`);

Values in process.env are always strings. Set one for a run with PORT=8080 node app.js on Linux and Mac, or $env:PORT=8080; node app.js in PowerShell. Node 20 and later can also load a file with node --env-file=.env app.js.

Never put secrets such as API keys directly in your code, and never commit the .env file. Keep it in .gitignore.

Built-in modules

Node ships with useful modules that need no installing. Import them with the node: prefix: node:fs for files, node:path for file paths, node:http for servers, node:os for system information, node:crypto for hashing and random values, and node:test for testing. The next lessons use some of them.

Common mistakes

  • **Running node in the wrong folder.** Cannot find module often means you are one folder off.
  • **Forgetting "type": "module".** Then import fails with "Cannot use import statement outside a module".
  • **Committing node_modules.** It can have thousands of files.
  • Deleting the lock file when something breaks. You lose the exact versions that worked.
  • **Treating process.env values as numbers.** They are strings.
  • Installing global packages for project needs. Use local installs and npx so every developer gets the same tool versions.

Try it yourself

  1. Create a project with npm init -y, set "type": "module", and add a start script.
  2. Install dayjs (or another small package) and print today's date in a custom format.
  3. Extend greet.js to take a --times 3 option and print the greeting that many times.
  4. Read a PORT environment variable and print a clear message when it is missing.
javascript
// greet.js
const args = process.argv.slice(2);
const name = args[0] ?? "friend";
const shout = args.includes("--shout");

let message = `Hello, ${name}!`;
if (shout) message = message.toUpperCase();

console.log(message);
console.log("Node version:", process.version);
console.log("Running in:", process.cwd());

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account