Thuta Learning
Node.js
BasicWeb DevelopmentBeginner

Get Started (Setup)

Node.jsLesson 325 min

What you'll walk away with

  • Install an LTS release of Node and verify it with node -v and npm -v
  • Create package.json with npm init -y and explain its main fields
  • Record the Node version a project needs with the engines field and an .nvmrc file
  • Run code through npm scripts such as start, dev (with --watch) and test

Explain it simply

Explain it simply

Setting up is like preparing a kitchen before you cook. Node.js is the stove, npm is the person who fetches ingredients, and package.json is the recipe card pinned to the wall: which ingredients the dish needs, how to start cooking it and which kind of stove it expects.

With a good card, anyone who walks into the kitchen can cook the same dish. If the recipe lives only in your head, nobody else can.

Problem → Why → Solution

The problem: "it works on my machine"

The app runs perfectly on your laptop. A teammate clones the project, runs it and it crashes: their machine has Node 16, and your code calls fetch(), which only became built in with Node 18. Which command starts the app, and which file is the entry point, also live only in your head.

terminal
# Your laptop                        # Teammate's laptop
$ node -v                            $ node -v
v22.11.0                             v16.20.2
$ node src/index.js                  $ node src/index.js
Fetched 3 users                      ReferenceError: fetch is not defined

Why does this happen?

The project never wrote down the Node version it needs, its module type or how to run it. The engines, type and scripts fields in package.json, plus an .nvmrc file, make those facts travel with the project.

Core concept: pick a version, write it down in package.json

Node.js ships a new major version every six months. Even-numbered majors (20, 22, 24) become LTS (Long-Term Support) releases and receive security fixes for years; odd-numbered ones (21, 23) are short-lived "Current" releases best kept for experiments. This course uses Node 22 or a newer LTS.

Install it with the installer from nodejs.org, or use a version manager such as nvm, fnm or nvm-windows to switch between versions. npm (the package manager) and npx (which runs commands from packages) come bundled with Node. After installing, open a new terminal and run node -v and npm -v; if both print a version number, you are ready.

package.json defines a project. npm init -y creates one with default values, and npm pkg set edits fields from the command line. "type": "module" tells Node to treat the project's .js files as ES modules. Commands in "scripts" run with npm run <name>, with npm start and npm test as shortcuts. "engines" declares the Node version you need; by default npm only prints an EBADENGINE warning on a mismatch and installs anyway.

When you install a package, for example npm install express, npm downloads it into the node_modules folder, records a version range under dependencies in package.json and writes the exact installed version into package-lock.json. Tools needed only during development, such as a linter, go under devDependencies with --save-dev. A teammate then gets everything back with a single npm install.

File / fieldWhat it is for
package.json → scriptsShared commands for the whole team (start, dev, test)
package.json → enginesThe supported Node range, such as ">=22"
package-lock.jsonExact installed versions; commit it to git
.nvmrcThe Node version nvm, fnm and CI read (such as 22)
node_modules/Installed packages; list it in .gitignore
Mental model: the setup pipeline
  1. Install an LTS Node
  2. Check node -v and npm -v
  3. npm init -y creates package.json
  4. Fill in type, engines, scripts
  5. Run everything through npm run

Move every fact you would otherwise remember into a project file.

General pattern: a minimal package.json

package.json
{
  "name": "project-name",
  "type": "module",
  "scripts": {
    "start": "node path/to/entry.js",
    "script-name": "command to run"
  },
  "engines": { "node": ">=22" }
}

name identifies the project and type marks .js files as ES modules. Each key in scripts is a command you run with npm run script-name. engines declares which Node versions the project expects.

Example: a script that checks your setup

Instead of eyeballing node -v, let Node check itself. This script tests the major version, the built-in fetch and import.meta.dirname, then prints PASS or FAIL. If any check fails it sets process.exitCode to 1, so tools such as CI notice the failure too.

check-setup.mjs
// check-setup.mjs - run it with: node check-setup.mjs
const MIN_MAJOR = 22;
const major = Number(process.versions.node.split(".")[0]);

const checks = [
  [`Node.js major version is ${MIN_MAJOR} or newer`, major >= MIN_MAJOR],
  ["Global fetch() is built in", typeof fetch === "function"],
  ["import.meta.dirname is available", typeof import.meta.dirname === "string"],
];

for (const [label, ok] of checks) {
  console.log(`${ok ? "PASS" : "FAIL"}  ${label}`);
}

const failed = checks.filter(([, ok]) => !ok).length;
console.log(failed === 0 ? "Setup looks good." : `${failed} check(s) failed.`);
if (failed > 0) process.exitCode = 1;

Code breakdown

  1. Line 3const major = Number(process.versions.node.split(".")[0]);

    process.versions.node is a string such as "22.20.0" (without the v that node -v prints). Taking the first part and converting it to a number makes a >= comparison possible.

  2. Lines 5-9const checks = [

    Each check is a small [label, true/false] array. The version, fetch and import.meta.dirname checks are all features this course relies on.

  3. Line 8typeof import.meta.dirname === "string"

    import.meta.dirname is an ES module's folder path. Because of this line the file must run as .mjs (or inside a "type": "module" project); in CommonJS, import.meta is a syntax error.

  4. Line 17if (failed > 0) process.exitCode = 1;

    Setting process.exitCode is gentler than process.exit(1): the program finishes writing its output, then ends with code 1. Shell scripts and CI treat any non-zero code as a failure.

You should see
PASS  Node.js major version is 22 or newer
PASS  Global fetch() is built in
PASS  import.meta.dirname is available
Setup looks good.

Building a new project, command by command

terminal
node -v                        # e.g. v22.20.0
npm -v                         # e.g. 10.9.3
mkdir nodejs-practice && cd nodejs-practice
npm init -y                    # creates package.json
npm pkg set type=module
npm pkg set engines.node=">=22"
npm pkg set scripts.start="node src/index.js"
npm pkg set scripts.dev="node --watch src/index.js"
npm pkg set scripts.test="node --test"
echo "22" > .nvmrc

node --watch restarts the process whenever a file changes, so you do not need an extra package like nodemon. node --test is the test runner built into Node, covered in the Advanced chapter. Run the scripts with npm run dev, npm start and npm test.

Open package.json after these commands and read it: every npm pkg set call added one field, and you could have typed them by hand just as well. The commands are simply quicker and avoid JSON typos such as a trailing comma, which would make every npm command fail until you fix it.

In real projects

How teams use this in real projects

In team projects, a long "how to run this" paragraph in the README usually shrinks to two commands: npm install and npm run dev. Scripts become the team's shared commands for build, lint, test and database migrations, so a new hire can run the project on day one. Nobody has to remember long flags, because the exact command lives in one file.

The version is aligned everywhere too. GitHub Actions' setup-node step can read .nvmrc as its node-version-file, and Docker images pin the version with tags such as node:22-slim. CI uses npm ci instead of npm install: it installs exactly what package-lock.json lists and fails if the lockfile and package.json disagree, so developer laptops and servers get identical dependencies.

Common mistakes

Common mistakes

1. Testing in a terminal opened before the install

A terminal opened before the install does not know the new PATH, so Windows says "'node' is not recognized as an internal or external command" and macOS/Linux say "command not found". Close and reopen the terminal, or all of VS Code if you use its terminal.

2. Relying on globally installed tools

After npm install -g nodemon, a script that calls nodemon breaks on a teammate's machine that lacks it. Add tools to devDependencies with npm install --save-dev (npm scripts find node_modules/.bin automatically), or use a built-in feature such as node --watch.

3. Committing node_modules but not the lockfile

node_modules can be hundreds of megabytes and may differ per operating system, so it belongs in .gitignore. package-lock.json must be committed, or each install can resolve different versions.

Best practices

Best practices

  • Keep both .nvmrc and engines in every project: one serves version managers, the other serves npm.
  • Turn every "how to run or test this" instruction into an npm script instead of a README paragraph.
  • Installing Node through a version manager avoids sudo for global packages and the permission errors that come with it.
  • Upgrade the Node major version on purpose, in its own commit, and run the tests before and after the switch.

Mini challenge

Mini challenge: a package.json checker

Write checkPackage(), which takes a package.json object and reports what is missing for a reproducible project. Try it on a good package and a sloppy one.

  • Check name, "type": "module", scripts.start and scripts.test
  • Check with a regular expression that engines.node looks like ">=22"
  • Return the problems as an array (an empty array when all is well)
  • Print "OK" or the list of problems for each package
check-package.mjs
// check-package.mjs - does a package.json describe a reproducible project?
function checkPackage(pkg) {
  const problems = [];
  // TODO: name, type === "module", scripts.start, scripts.test
  // TODO: engines.node should match /^>=\s*(\d+)/
  return problems;
}

const good = JSON.parse(`{ /* TODO: a complete package.json */ }`);
const sloppy = { name: "copied-project", scripts: { start: "node index.js" } };

// TODO: print "good: ..." and "sloppy: ..." using checkPackage()

Expected: The output should be: good: OK sloppy: type should be "module"; missing scripts.test; engines.node should look like ">=22"

Show hint

Optional chaining such as pkg.scripts?.start returns undefined instead of throwing when scripts is missing entirely. /^>=\s*(\d+)/.exec(text)?.[1] extracts the version number.

Show solution
check-package.mjs
// check-package.mjs - does a package.json describe a reproducible project?
function checkPackage(pkg) {
  const problems = [];
  if (!pkg.name) problems.push("missing name");
  if (pkg.type !== "module") problems.push('type should be "module"');
  if (!pkg.scripts?.start) problems.push("missing scripts.start");
  if (!pkg.scripts?.test) problems.push("missing scripts.test");

  const minMajor = Number(/^>=\s*(\d+)/.exec(pkg.engines?.node ?? "")?.[1]);
  if (!minMajor) problems.push('engines.node should look like ">=22"');
  return problems;
}

const good = JSON.parse(`{
  "name": "nodejs-practice",
  "type": "module",
  "scripts": { "start": "node src/index.js", "test": "node --test" },
  "engines": { "node": ">=22" }
}`);
const sloppy = { name: "copied-project", scripts: { start: "node index.js" } };

for (const [label, pkg] of [["good", good], ["sloppy", sloppy]]) {
  const found = checkPackage(pkg);
  console.log(`${label}: ${found.length === 0 ? "OK" : found.join("; ")}`);
}

Quick quiz 1 / 3

Which Node.js releases become LTS releases?

Quick quiz 2 / 3

package.json has "engines": { "node": ">=22" } and a teammate runs npm install on Node 20. What happens by default?

Quick quiz 3 / 3

You added "dev": "node --watch src/index.js" to scripts. How do you run it?

What to remember

  • Even-numbered Node versions become LTS; this course uses Node 22 or newer.
  • Create package.json with npm init -y, then fill in type, engines and scripts.
  • Commit package-lock.json and list node_modules in .gitignore.
  • Run built-ins such as node --watch and node --test through npm scripts.

Downloading and installing Node.js — Node.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.