Basic

Project setup with npm

Real projects use many libraries. `npm` is the tool that downloads and manages them. Learn `package.json`, `npm init`, and `npm install express` so your project is organised like a real one.

About 2 min of reading

Data Flow

npm reads package.json, downloads each listed dependency from the internet, and saves them into node_modules.
1 You run npm install
↓
2 npm reads package.json dependencies
↓
3 npm contacts the npm registry online
↓
4 npm downloads each library's code
↓
5 Files are saved into node_modules
↓
6 Your app can now require them
Why this works
Why node_modules is ignored

You never commit node_modules to version control. It can contain thousands of files.

Instead, package.json records the versions you need, and anyone cloning your project runs npm install to recreate the folder. A file called .gitignore tells git to skip node_modules:

node_modules/

This keeps your repository small and lets your app be rebuilt anywhere.

Examples

Initialising a project

In a new folder run:

npm init -y
npm install express

This creates **package.json*: a small file that records your project's name, version, and dependencies. It looks like:

{
  "name": "my-app",
  "version": "1.0.0",
  "dependencies": {
    "express": "^4.18.2"
  }
}

The node_modules folder now contains the Express code. You never edit it, you only use it with require.

The package.json file

package.json is the identity card of your project. Every line matters.

  • name: the project's identifier.
  • version: follows semantic versioning: major.minor.patch.
  • dependencies: the libraries your app needs to run.
  • scripts: shortcuts for commands, like "start": "node server.js".

{
  "scripts": {
    "start": "node server.js"
  }
}

Now npm start is the same as typing node server.js. Small shortcuts add up over a big project.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Your first web server
Previous Lesson
Your first web server
Next Lesson
Routes and URLs
Routes and URLs →