NPM

Node Package Manager (NPM), is the default and most popular package manage for Node.js.

It's capable of manging dependencies for Node.js projects.

A node project is defined by having a package.json in the root of the project.

package.json

package.json contains meta information about the project, dependencies, and scripts.

It's what defines a node project, and should be located at the root of the project.

You can make node create this file, but it's also very possible to create it yourself.

For example, to create a very basic node project with express as a dependency;

package.json

Copy

{
  "dependencies": {
    "express": "4.21.2"
  }
}

You can then use npm install, and npm will install all dependencies. modules will be installed locally if not otherwise specified, they'll be put into a folder called node_modules

terminal

Copy

$ npm install

Alternatively you can use the npm init -y command to get npm to auto generate a package.json

terminal

Copy

$ npm init -y

the -y flag automatically accepts all prompts to default value

The generated package.json will look like this if the folder name is app;

package.json

Copy

{
  "name": "app",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

type module

You can define the type of your project in package.js

by default, it's commonjs

Before ECMAScript 6, JavaScript didn't have a traditional import

That meant Node, had to implement their own.

JS

Copy

const express = require('express');

but after ECMAScript 6, you can use the module system, by setting type to module

package.json

Copy

"type": "module"

This is very nice since it streamlines imports and exports between the frontend and backend.

But is also just nicer to work with in general.

JS

Copy

import express from 'express';

npm run

run is a command from npm, that enables you to run scripts defined in the package.json

For example consider the generated package.json 'scripts' key from npm init -y

package.json scripts

Copy

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  }

you can execute the 'test' script by using npm run test

terminal

Copy

$ npm run test

> app@1.0.0 test
> echo "Error: no test specified" && exit 1

"Error: no test specified"

node_modules

node_modules is where all dependencies are installed to when using npm install.

It is a local copy of all modules/dependencies needed to run the project.

It should not be commited to version control

Instead each developer should run npm install locally.