How to get started with node.js

I had the opportunity to help a friend enrolled in a code bootcamp. Their language ecosystem of choice was node.js which I had never experience with, so I had to quickly familiarize myself with the basics. I document the basics here just in case I ever need to do this again.

Install

Following the (alternative) guide from nodejs.org:

$ brew install node
...

Here are the versions I have as of this writing (spring 2021):

$ which npm
/usr/local/bin/npm

$  npm -v
7.6.3

$ which node
/usr/local/bin/node

$ node -v
v15.12.0

Create a project

Create and initialize a project:

$ mkdir proj
$ cd proj
$ npm init
...

$ ls
package.json

Install the request package:

$ npm install request
...

$ cat package.json
{
  "name": "proj",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "request": "^2.88.2"
  }
}

REPL

Start REPL:

$ node
Welcome to Node.js v15.12.0.
Type ".help" for more information.
>

Within REPL:

> 3 + 2
5

> console.log('3 + 2 = ', 3 + 2)
3 + 2 = 5
undefined

>.exit

Run a script

$ cat script.js
const request = require('request');
request("http://worldtimeapi.org/api/timezone/America/Vancouver", (error, resp, body) => {
    console.log('time is: ', JSON.parse(body)["datetime"]);
});

$ node script.js
time is:  2021-05-03T23:37:36.240126-07:00

This was enough to help the friend with loops, data structures, and simple call-backs.