Node.js and npm basics
Course contents (16 lessons)
- Modern syntax
- Destructuring, spread and rest
- ES modules: import and export
- Objects, this and errors
- Classes and prototypes
- Understanding this in JavaScript
- Error handling: try, catch and custom errors
- Asynchronous JavaScript
- The event loop: how JavaScript handles waiting
- From callbacks to promises to async/await
- Fetch and REST APIs
- Working in the browser
- Local storage and session storage
- Debugging with browser DevTools
- Performance basics: debounce and throttle
- Node.js essentials
- Node.js and npm basics
- Working with files in Node.js
- A tiny HTTP server with Node.js
- Testing and the final project
- Testing basics with the Node.js test runner
- 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.jsonandpackage-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 withnpm install. - **Run
npm cion 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
nodein the wrong folder.**Cannot find moduleoften means you are one folder off. - **Forgetting
"type": "module".** Thenimportfails 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.envvalues as numbers.** They are strings. - Installing global packages for project needs. Use local installs and
npxso every developer gets the same tool versions.
Try it yourself
- Create a project with
npm init -y, set"type": "module", and add astartscript. - Install
dayjs(or another small package) and print today's date in a custom format. - Extend
greet.jsto take a--times 3option and print the greeting that many times. - Read a
PORTenvironment variable and print a clear message when it is missing.
// 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