We install Node using the double click installer from nodejs.org, or using a package manager like brew, apt-get or aptitude.
First install Node. If you have node already you can skip this step. Type node —version into a console to find out if you have it.
If not, go on and install it.
Option 1 - install from the website
Visit nodejs.org and download the installer for your platform.
Option 2 - install via brew (OSX only)
If you’re on a Macintosh, you can install via brew. Substitute brew for aptitude, or another package manager if you prefer a different flavour of Linux.
brew install nodejs
You may need to restart your console.
The Node console
You can open up a NodeJS console from the command line with the node command, like so:
Exercise - Node Console
Let’s try out the Node console and execute a command. Drop into the node console by typing node. Now try the following:
- Add 10 + 10.
- Use console.log(‘hello world’) to output hello world.
- Find out how many seconds there are in a year. How many seconds there are in a century. I don’t know the answer to this. See, you’re smarter than me already.
Running a program
Exercise - Executing a program
You can make Node output to the terminal using console.log(). Create a file called app.js and add a line that uses console.log() to tell Node write “Hello World” to the console.
Run your program from the console using the node command.
You should see hello world.
You can find the current time using:
Create a node program that tells you the current time and date.
You can get a date object for a specific date using:
new Date(2022, 11, 25);
You can subtract one date object from another to get the number of milliseconds between them.
dateOne - dateTwo;
Make a timeTillChristmas program that tells you how many seconds there are until Christmas.
Optionally make it tell you how many days there are.