Setting Up your Environment: Install NodeJS
- Ch. 6 begins by asking you to install VirtualBox and Vagrant to create a virtual machine on your computer
- But we will skip VirtualBox and Vagrant– no virtual machine necessary!
- Just install NodeJS, if you have not already done so
Hello, HTTP! (p. 189)
The example shown on p. 189 creates an HTTP server with 7 lines of NodeJS.
Here’s how to Run the HTTP server example.
Node Package Manager (NPM)
Node comes with another program called the Node Package Manager (or NPM for short). This command-line tool allows us to easily install Node modules (a.k.a., packages).
The first package you will install is Express.
Learn npm, the Node Package Manager.
Modules and Express (p. 191-2)
Node’s HTTP module is a bare-bones server. Once you want to start sending HTML, CSS, JavaScript and image files from the server, things get more complicated.
Enter Express.
Express is a NodeJS module (aka, package). The first Node/Express server is shown on p. 192.
Here’s how to run it:
Our First Express Server
- Create a new directory, ~/Documents/repos/281/examples/express
- cd to the express directory.
- Create a package.json file.
$ npm init --yes
- Install the latest version of Express using npm.
$ npm install express --save
- Download this Express server to your Express folder.
- Open server-192.js in Atom.
- Start the Express server:
$ node server-192.js
- Open localhost:3000/hello in Chrome.
- Stop the server (control-c).
Our Second Express Server
The second Node/Express server is shown on p. 194. Here’s how to run it:
- Create a new directory, ~/Documents/repos/281/examples/app/Express/client/
- In Atom, create a new file named index.html in the client directory. Use Emmet to turn it into a Hello, World! web page.
- Download this Express server to your Express directory (not the client directory).
The server code lives in the Express directory, all client code lives in the client directory.
- Open server-194.js in Atom.
- Start the server:
$ node server-194.js
- Test these routes Chrome:
127.0.0.1:3000/
localhost:3000/hello
127.0.0.1:3000/goodbye - Stop the server (control-c).
Notes
- In server-194.js, Node’s app.use statement creates a static file server directory. This means any request sent to the server will initially be resolved by the static file directory (client) before the route handlers are invoked.
- The client directory is not part of any route or URL endpoint.
- Your Express server automatically looks in this directory for static web pages, images, CSS files, and JavaScript files.
You are can now serve AJAX apps from your own computer.
Your computer is now a testing server.
Exercises
- Create an images folder in the client directory, add an image to it, and then add an img element to index.html to display the image on the web page.
- Create a stylesheets folder in the client directory, add a .css file to it, and then link the .css file to index.html