Week 3 - Getting started with NodeJS & Heroku
Introduction to webservers & NodeJS. Getting set up locally and on Heroku & a simple NodeJS server. Discuss the command line tools, Git & NPM (node package manager).
Servers & Clients (Quick Refresh)
- Servers are programs/scripts
- that receive requests from clients
- via open ports / sockets
- respond with data and services
Node & Heroku
In this session we will cover
Requirements for this tutorial
- Get and install NodeJS
- Git - download install if needed
- You'll need a Heroku account, register here
- Download and install Heroku toolbelt
Intro to TCP and HTTP Servers
The most basic server is a TCP server. TCP, transmission control protocol is a protocol developed for the internet to get data from one network device to another.
One computer will run a program or script to act as the server to open its ports to other computers that will connect as clients. The main server script can accept 1 or more clients depending on how the program is setup.
The connection between the TCP server and client(s) is persistent, once a connection is made it remains until one side disconnects.
HTTP is built upon the TCP protocol. HTTP, Hypertext Transfer Protocol, is the connection method for the Web. A Web server (a program) will open a port and accept incoming connections. Web clients connect to server and make a request for web pages, images, CSS, JavaScript. Clients can be browsers, mobile apps and even other servers all making requests.
When a request is received, the HTTP web server will respond appropriately with the data and some other meta information like status code; 200 - successful, 404 - not found, 500 - server error. After the web server responds the connection between the server and client is closed. For every request a connection is made and closed. Being an HTTP web server is a tiring job.
Intro to NodeJS
NodeJS (or Node) is a JavaScript framework to build HTTP web and TCP socket servers. These servers are run on code written in JavaScript using various node module libraries. Similar to Processing when you might include a library to perform a special function, Node's modules are organized by function.
Installing & Testing NodeJS
After you have downloaded Node, click and install. You interact with Node through the command line interface, no icons or applications will be displayed on your Desktop or Applications folder.
Node command line interface (CLI)
Open Terminal(from Applications/Utilities) and type
node
This is your prompt on the NodeJS command line. You can run any JavaScript from the command except for commands related to the web browser. For example
> 1+1
2
> var dog = "Sheldon"
undefined
> dog
'Sheldon'
> if ('a'=='a') { console.log("those match") }
those match
undefined
Now if we try to use a browser JavaScript function we will see that NodeJS will throw an error.
> alert("hello world")
ReferenceError: alert is not defined
at repl:1:2
at REPLServer.eval (repl.js:80:21)
at Interface. (repl.js:182:12)
at Interface.emit (events.js:67:17)
at Interface._onLine (readline.js:162:10)
at Interface._line (readline.js:426:8)
at Interface._ttyWrite (readline.js:603:14)
at ReadStream. (readline.js:82:12)
at ReadStream.emit (events.js:88:20)
at ReadStream._emitKey (tty.js:309:10)
To exit the Node console, press Contrl+C twice
Running a JavaScript file with Node
Create a new .js file called colors.js. Copy and paste the follow sample code.
// create an array of colors
var colors = ['Red','Blue','Green','Magenta'];
// loop and print each array number + color
for (i=0; i < colors.length; i++) {
console.log(i + " " + colors[i]);
}
Save the file to your computer and open the Terminal. Inside the Terminal type,
node ***!drag file from Finder to terminal window! ***
After entering the filepath your terminal should
node /Users/john/Desktop/DWD/colors.js
Press enter to run the code.
0 Red
1 Blue
2 Green
3 Magenta
TCP Node Server
The following example will create a simple TCP server that will echo back any message received by a client. This example uses NodeJS's NET module, which is included in the standard NodeJS install, http://nodejs.org/api/net.html.
Copy JavaScript into a new file tcp_echo.js
Start Server, navigate to code directory in Terminal:
node tcp_echo.js
In another new Terminal window, connect to TCP Echo server
telnet localhost 5000
Enter a message in the connected Terminal window and hit return key.
HTTP Node Server
You can create a HTTP web server with NodeJS easily to receive and respond to HTTP requests. This example uses the standard HTTP NodeJS module http://nodejs.org/api/http.html.
Copy the JavaScript into a new file web.js
Start the server inside Terminal. Run the command
node web.js
View the web page in your browser, http://localhost:8000
Heroku Platform
Heroku is a service to host your web application in the 'cloud'. Their tools allow you to easily increase the number of servers, database and performance of your web site if you have an unexpected wave of traffic. This ease of use to increase capacity in the servers allows a web site to focus on the application and not the infrastructure while their project grows.
Hosting your web application in the 'cloud' is different that hosting it on a shared web server at Dreamhost or Mediatemple where your ability to grow your web site's serving capacity is fixed and usually requires moving files to a new server when upgrading. With services like Heroku and DotCloud.com you push your code to their servers and scale as needed from the browser control panel or command line interface in Terminal.
Setup and files for Heroku
For the rest of the semester we will be running web servers locally on our computers for development. When the code is ready to be publicly available on the Internet we will push our code to Heroku, which will serve as our web host.
There is some initial setup to get our code onto Heroku. Heroku needs a few files to know what code should be running and what libraries need to be installed.
Heroku Boilerplate repository
Download and open the boilerplate code https://github.com/johnschimmel/Heroku-Boilerplate
The files inside need to be in every web app you push to Heroku for it to be run correctly. Each app can be configured with different requirements and codebase.
web.js - this is the main script that creates a server and responds to client requests.
package.json - this file is required on Heroku, it is a configuration file that provides the name and node modules as well as the NodeJS and NPM versions that should be used for execution.
Procfile - this file tells Heroku which script to run when deployed. We define a 'web' process pointing to web.js
.gitignore - this file might be invisible because it starts with a '.' this file declares what files Git should ignore. The current file is ignoring the node_modules directory and a .env file.
In Terminal, open the Heroku Boilerplate folder. (Keep things organized, move the boilerplate folder into your DWD folder)
The package.json file will keep track of any node modules (libraries) that you use. Below you can see that the modules 'express' version '3.0.x' is a dependency for this project.
package.json
{
"name": "mynodeapp",
"version": "0.0.1",
"dependencies": {
"express": "3.0.x"
},
"engines" : {
"node" : "0.8.x",
"npm" : "1.1.x"
}
}
For today's class we are not using Express but will include it as a dependency in our package.json
Install Node Modules
In Terminal, open the boilerplate folder and run the following command
npm install
This command runs NPM, checks for any new dependencies and installs anything that is needed. New node modules will be installed in the node_modules directory (which is also created if it does not exist).
Start local server
You can run the web server locally by typing
foreman start
And accessing the local server at http://localhost:8000
You can stop the server by pressing Control+C
Deploy to Heroku
Follow Heroku's instructions for deployment here, https://devcenter.heroku.com/articles/nodejs#store-your-app-in-git
Git, init, add, commit, push
- Create Git repo
- Add all files to repo
- Commit changes
In Terminal, inside your code directory run the following commands
git init
git add .
git commit -am "initial commit"
Push code to Heroku
Heroku Login via Terminal
If you have never logged into Heroku via the Terminal, run 'heroku login'
heroku login
Log in with your Heroku account and credentials.
Create a Heroku app
In Terminal, inside the code directory you can create a new Heroku app with the following command 'heroku create.
heroku create
The response will look like
Creating sharp-rain-871... done, stack is cedar
http://sharp-rain-871.herokuapp.com/ | git@heroku.com:sharp-rain-871.git
Git remote heroku added
View Git/Heroku remote path
If successful Heroku toolbelt also adds a new Git remote path. You can view your Git repo's remote paths with the command 'git remote -v'
git remote -v
The Terminal will display
heroku git@heroku.com:thawing-sierra-2838.git (fetch)
heroku git@heroku.com:thawing-sierra-2838.git (push)
Push Code to Heroku
git push heroku master
This process can take 15 seconds to a few minutes to finish depending on how many dependencies need to be installed.
Open Heroku App
heroku open
Rename your Heroku app
Most likely Herok gave your app a crazy name, you can rename it easily with the command 'heroku rename __'
heroku rename PUTAUNIQUENAMEHEREFORALLTOENJOY
If that unique name is available, heroku will rename your app and you will have a better looking subdomain.
Assignment
- Using the sample web server code again, make a server that can serve 3 webpages. Get this server working locally.
- Commit your changes and push this server to Heroku.
- Tell your friends and add your web app url to the comment form below.