Advanced Web Development

Week 1: Introduction to Node.js

By Eric Moynihan

Requirements

Windows, Mac or Linux

Visual Studio Code Node.JS (incl. NPM)

What is Node.js?

Node.js runs JavaScript on a server. This differs it from normal JavaScript since it was originally designed to run inside a Web Browser.

Installing on Windows

Installing on Windows is simple. Just go to their website and download the installer. Just make sure the option's ticked to add it to your PATH.

Running Node

So as long as node is added to your PATH, you should be able to do the following:

  1. Press Windows Key + R
  2. Type cmd into the input box
  3. In the black command prompt, type 'node -v'
  4. If it prints v11.x.x then node is installed correctly

Example node.js script

So you can code in Node.js as if you were just typing normal JavaScript.

  1. Open the File Explorer
  2. Open Documents
  3. Right Click, then select New > Folder
  4. Name the folder node_example
  1. Now open Visual Studio Code
  2. In vscode, click on File > Open and open node_example
  3. Now create a new file and call it example.js and open the file
  4. Now we can start coding!

Features

When logging through console, it will output to the terminal you launch the script in.


  console.log("Hello World");
          

The language is fundamentally the same as the JS you use in a browser.

Just remember that it uses a more modern *flavour* of js called ES6.

Features of ES6

ES6 brings with it extra features for basic things like for loops. See the example below and figure out what is does:


  // Old JS
  var arr = ["A", "B", "C"];
  for (var i in arr) {
    console.log(arr[i]);
  }
  // ES6
  let arr = ["A", "B", "C"];
  for (let a of arr) {
    console.log(a);
  }
          

Modules

Node.JS can separate your code into unique 'modules'. Modules can be imported by passing their name as a string to the built in function require().

A module can be one of the following:

  • A folder with a package.json file containing a "main" field.
  • A folder with an index.js file in it.
  • A JavaScript file.

Next Week

We will cover package.json, NPM and Express.js