Learn Javascript

NPM & Node

Introduction to NPM and Node

slides | md

About Node

  • Node.js is Javascript for the command line.
  • Use Node to create web servers, APIs, database-driven websites, standalone software, and much more.
  • Use NPM (Node Package Manager) to install, manage, and incorporate open source software packages (dependencies) in your projects.

Node Installation

There are several ways to install Node (which includes NPM) on your machine

  1. Use an installer via node website (fastest, but difficult to upgrade).
  2. Use a system package manager like Homebrew or Scoop (easy to upgrade)
  3. Use nvm (the most flexible method, but takes longer).

I recommend #2. Choose your OS and install Node below.

👉 Install Node & NPM

Mac

  1. Install Homebrew (Mac package manager) using their instructions
  2. Install Node using Homebrew
brew install node
Tutorial for updating MacOS installations

Windows

⚠️ Many Unix commands do not work in Windows PowerShell. Install and use Git Bash instead.

  1. Install Scoop (Windows package manager) using their instructions
  2. Install Node using Scoop
  scoop bucket add main
  scoop install main/nodejs-lts

👉 Confirm your Node version

Run these to make sure that Node installed correctly:

node -v     # check node version
npm -v      # check npm version

👉 Open Node interactive shell

Node is just Javascript, so almost any code will run.

  1. Type node on the command line and press return to open the interactive shell.
  2. At the > prompt, type 1+1 and press return. Node will evaluate your expression and return the result.
> 1+1
2
  1. Type Ctl+C to cancel in the shell

👉 Run a script with Node

  1. Create a new folder named: cron-demo and open it in VS Code (in Mac you can just drag the folder from the finder to the VS Code icon in the dock)
  2. Create a file in this folder named index.js and paste the below code.
let greeting = "Hello, from Node";
console.log(greeting);
  1. In the VS Code Terminal, run* the script with
node index.js
  1. The name index.js is arbitrary. Other names like server.js and app.js are also popular for different use cases.
  2. Notice that Node stops automatically after it runs all the code.

👉 Initialize a new project with NPM

Every Node.js project has a package.json to store project dependencies and other metadata.

  1. Open cron-demo in VS Code (above)
  2. Run npm init to initialize a new project. Press return at each prompt. This creates a package.json file with data you entered.
  3. Open your new package.json file. Confirm the main field is set to index.js.
  4. Add a new sub-property under scripts. Add a comma after the test property, then add "start": "node index.js" below it.
  5. Run npm run start which runs the command stored in start.
Example
{
  "name": "cron-demo",
  "version": "1.0.0",
  "description": "",
  "license": "ISC",
  "author": "",
  "type": "commonjs",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  }
}

👉 Install Nodemon using NPM

Nodemon is an NPM package that automatically restarts your node application when it detects file changes your the project directory.

  1. Install the nodemon package globally npm install -g nodemon (the -g flag makes it global)
  2. Run index.js using nodemon (instead of node) nodemon index.js
  3. Edit and save index.js. Nodemon will restart your script each time you save.
  4. Exit the process with Ctl+C (this exits any process on the Terminal).
  5. Run nodemon again (omit the filename) to default to the script in main.
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`

👉 Use the Cron package

Cron is an NPM package that executes scripts on a schedule (e.g. each/second, once/day) or at particular times. Use it to automate any common task like database backups, etc..

  1. Run npm i cron --save in the Terminal (i is a shortcut for install, --save adds a dependency to your project's package.json)
  2. In package.json a new dependency has been added, as well as a new node_modules folder, where the cron package and packages it uses was just installed.
  3. Add the code from the next slide to your index.js file.
  4. Run it with nodemon index.js in the Terminal.
  5. Use crontab.guru to experiment with the time.

👉 Cron sample code

// require the package
var CronJob = require('cron').CronJob;
// create a new instance
var job = new CronJob(
	'* * * * * *',
	function() {
		console.log('The local time is: '+ new Date().toLocaleString());
	},
	null, true, 'America/New_York'
);

More about packages

  • Every package has a README with documentation. Explore it on github or npmjs.com
  • The package-lock.json manages the dependencies of your project dependencies. Do not edit this file.
  • Never commit the node_modules folder to your git repository. To run your project on another machine (or server), just clone it and run npm install install all your dependencies.

👉 Create a Git repo and commit a .gitignore file

  1. With your project open in VS Code, type in the Terminal to create a repo
git init
  1. Notice all your files are now considered additions
  2. Before you commit, add a .gitignore file using
touch .gitignore
  1. Paste the text to the right in the file and save.
  2. Drag your project folder into Github Desktop. Then publish it.
# Windows
Thumbs.db
desktop.ini

# OS X
.DS_Store
.Spotlight-V100
.Trashes
._*

# JS
node_modules

CommonJS vs Modules (ES)

If you see this message, you might be mixing old and new methods for importing code. See Modules

ReferenceError: require is not defined in ES module scope, you can use import instead

CommonJS

The old way for importing packages and reusable code in your projects.
var one = require('./one.js');

ESM

The new way. Now mostly universal.
import { two } from './two.js';
You have to add "type": "module" in package.json to use import

Next Steps

  1. Continue learning Node Express
  2. Examine code in demos/basic-node (modules and writing files) or see slides at end of this presentation
  3. Explore tutorials tutorialspoint, nodejs.dev, guru99.com, tutorialsteacher.com
  4. Check out sample projects using Node:

References

  1. Brown Ch1 Introducing Express (1-9) and Ch2 Getting Started with Node (11-20)
  2. w3schools nodejs, intro, command line, npm

Advanced Node Installation

  • Using NVM
  • Managing NPM packages

How to install Node using NVM

Node Version Manager (NVM) make it easy to install and use different versions of node via the command line. Reference

  1. Install Homebrew
  2. Update then install NVM
brew update
brew upgrade
brew install nvm

See these instructions for NVM, Node, NPM on Windows

How to install Node (versions) using NVM

The latest node version

nvm install v16.10.0
nvm ls
nvm use 16

The latest LTS (Long Term Support) node version

nvm install --lts
nvm ls
nvm use <NUMBER>

How to ... NVM

How to update NVM

brew update
brew upgrade # to install

How to update NPM using NVM

nvm install-latest-npm

How to upgrade NPM packages

npm-upgrade is an interactive CLI utility to easily update outdated NPM dependencies

// install utility globally
npm i -g npm-upgrade
// run in a project
npm-upgrade check

npm-upgrade

Install Node using NVM

While you can download and run a prebuilt installer NVM (Node Version Manager) let's you manage and upgrade your installation later.

  1. Install NVM with Homebrew (Mac only) or run the Node NVM install scripts (all platforms) one line at a time on the command line.
# installs NVM (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
  1. Use NVM to install Node
# download and install Node.js
nvm install 20

Presentation comments ...

<div class="twocolumn"> <div class="col"> 1. Open `cron-demo` in VS Code (above) 2. Run `npm init` to initialize a new project. Press return at each prompt. This creates a `package.json` file with data you entered. 3. Open your new `package.json` file. Confirm the `main` field is set to `index.js`. </div> <div class="col"> 4. Edit the `scripts` property. Add a comma to the end of the `test` property, then add `"start": "node index.js"` below it. 5. In the Terminal run, `npm run start` </div> </div>

TODO: Clean up all these projects