Node / NPM Cheat Sheet

Quick reminders of important node / npm commands.

Run a single js file

node file.js

Add a package.json file to make a folder into a package

Do this ONCE when you first make a new folder that you want to function as a package (something you can run and that you can install other packages into).

npm init

Then add scripts to the package.json to allow for easy execution of commands.

(Instead of npm init you can also copy/paste a package.json from some other project and then edit it as necessary.)

Run a script from your package.json

Any scripts you define can be run with:

npm run SCRIPTNAME

There is no major difference between npm run SCRIPTNAME and node FILE.js. If you have a script defined in your package.json like this:

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

You can either do

npm run start

or

node app.js

To run the app.js file. The main reason to use npm run is that it allows you to define scripts that do more than just run a single file. For example, you could have a script that runs your server with nodemon, or one that runs some tests, etc... You can also have scripts that run multiple commands in sequence (e.g. one that first builds your code and then runs it).

Add a package to your app

To make use of another package, you need to include it in your code. But unless that package is built into node, you also need to install it with:

npm install PACKAGE

It should be added to your package.json (and the lock file) and the package should be installed into the node_modules folder.

Install all the dependencies identified in the package.json

If you download a project from Github, it hopefully does not include the node_modules folder. So before you can use it, you need to install all the packages it uses. Rather than do that one by one, you can simply do:

npm install

That will install everything listed in the package.json file to your node_modules folder.

It is safe to run this even if you have packages installed already. If a teammate adds a new package to the package.json and you then pull those changes to your repository, you will want to run npm install to add any new packages to your node_modules.