First Node App
First Node App
Node.js is one of the biggest explosions in the past few years. Having the ability to run JavaScript (the clientside language many are familiar) on the server is an enticing notion.
Front-end developers that know JavaScript well can easily expand their knowledge to know back-end serverside code.
Node is built on Google Chromes V8 JavaScript runtime and sits as the server-side platform in your MEAN
application. So what does that mean? In a LAMP stack you have your web server (Apache, Nginx, etc.)
running with the server-side scripting language (PHP, Perl, Python) to create a dynamic website. The serverside code is used to create the application environment by extracting data from the database (MYSQL) and is
then interpreted by the web server to produce the web page.
When a new connection is requested, Apache creates a new thread or process to handle that request, which
makes it multithreaded. Often you will have a number of idle child processes standing by waiting to be
assigned to a new request. If you configure your server to only have 50 idle processes and 100 requests
come in, some users may experience a connection timeout until some of those processes are freed up. Of
course there are several ways to handle this scalability more efficiently, but in general Apache will use one
thread per request, so to support more and more users you will eventually need more and more servers.
This is where Node.js shines. Node is an event driven language that can play the same role as Apache. It
will interpret the client-side code to produce the web page. They are similar in that each new connection fires
a new event, but the main distinction comes from the fact that Node is asynchronous and single
threaded. Instead of using multiple threads that sit around waiting for a function or event to finish executing,
Node uses only one thread to handle all requests. Although this may seem inefficient at first glance, it actually
works out well given the asynchronous nature of Node.
Why Node?
Node lets us build real-time open APIs that we can consume and use with our applications. Transferring data
or applications like chat systems, status updates, or almost any other scenario that requires quick display of
real-time data is where Node does its best.
Getting Started
Installing Node
Make sure you have Node (http://nodejs.org) and npm (Node's package manager) installed. npm comes
bundled with Node so as long as you install Node, you'll have access to npm.
Once you've installed Node, make sure you have access to Node and npm from the command line. Let's
verify installation by checking version numbers. Go into your command line application and type node -v
and npm -v . You should see the following:
$ node -v
v0.12.0
$ npm -v
2.5.1
If you have trouble with the installation process, try restarting your computer and making sure that Node is in
your PATH. Check the Node installation page (https://github.com/joyent/node/wiki/installation#installing-onwindows) and npm install page (https://github.com/npm/npm/wiki/Troubleshooting) for more troubleshooting.
Now that we have Node and npm installed, let's get to our first app!
That seems overwhelming at first, but if you take it line by line, you can see that a lot of the attributes created
here make it easier for other developers to jump into the project. We'll look through all these different parts
later in the book, but here's a very simple package.json with only the required parts.
{
"name": "node-booklet-code",
"main": "server.js"
}
main tells Node which file to use when we want to start our applications. We'll name that file server.js for
all of our applications and that will be where we start our applications.
For more of the attributes that can be specified in our package.json files, here are the package.json docs
(https://www.npmjs.org/doc/files/package.json.html).
Now we can start up our Node application by going into our command line and typing: node server.js
$ node server.js
We should see our message logged to the console. Remember that since Node is JavaScript on the server,
the console will be on our server. This is in contrast with the client-side console that we'll find in our browser's
dev tools.
when file changes are made. This can become tedious when we are developing since we will
have to shut down and restart every time we make a change.
Luckily there is an npm package that will watch for file changes and restart our server when
changes are detected. This package is called nodemon (https://github.com/remy/nodemon) and
to install it, just go into your command line and type:
$ npm install -g nodemon
The -g modifier means that this package will be installed globally for your system. Now, instead
of using node server.js , we are able to use:
$ nodemon server.js
Feel free to go into your server.js file and make changes. Then watch the magic happen when
application restarts itself!
We'll be using nodemon for the rest of this booklet.
Installing Express
The packages for a specific Node application are defined in its package.json . To get packages installed,
you can employ one of two methods:
The --save modifier will let npm know that it should write that package to your package.json file. If you
run that command and go look in the package.json file, you'll notice it will be in a dependencies section
of your file. You'll also notice that a new folder called node_modules is created. This is where Node stores
the packages for a certain project.
This is what makes sharing projects between developers and collaborators very easy. Just send other users
your project and they run npm install to install everything in the dependencies section.
Since we now have Node and Express ready, let's use both to create an HTTP server and serve up an HTML
file to our users.
</body>
</html>
We'll be linking to the CSS framework Bootstrap (http://getbootstrap.com/) through Bootstrap CDN
(http://bootstrapcdn.com/) to help us get quick CSS styling for this demo.
Let's move forward and create our HTTP server in Node using Express. Delete everything in your
That file is all that is required to use Express to start an HTTP server and send an HTML file!
require() is the main way that we call packages in Node. Once we have created an Express application in
app , we can define routes on it using the HTTP variable. app.get() creates a GET route for / .
When creating routes, we will always have access to the req (request) and res (response). The request
contains information from the browser like HTTP agent, information passed in and more. The response is
what we will send back to the user. We are using sendfile() , there are more things that can be done like
sending back JSON data using res.json() .
We can start the server using app.listen() and passing in the port that we want 8080 .
Let's make sure everything works by going into the command line to process this file and start our server.
$ nodemon server.js
Installed Node
Processed a very simple file
Used npm to install a package
Create an HTTP server with Express
Serve an HTML file
Let's take this a step further and create an application that actually shows relevant data.
Requirements
Use Express as the Node framework
Use the Instagram Developer API
Use the instagram-node (https://www.npmjs.com/package/instagram-node) package
View popular Instagram photos
Template a Node app with EJS (http://www.embeddedjs.com/) and the EJS package
(https://www.npmjs.com/package/ejs)
Directory Structure
- public/
----- css/
---------- style.css
- views/
----- pages/
---------- index.ejs
----- partials/
---------- head.ejs
---------- header.ejs
---------- footer.ejs
- package.json
- server.js
We have the same structure to start our Node application. package.json and server.js are still there.
We will be serving public files (CSS/JS/images) from the public/ folder.
You'll notice that our views are separated into partials/ and pages/. Partials will be reusable components like
the header and footer of our site. It's good practice to separate these out so that we can keep our code DRY
(http://en.wikipedia.org/wiki/Don't_repeat_yourself).
EJS (https://www.npmjs.com/package/ejs) will be the templating engine and it is very commonly used within
Node applications. This helps in a number of ways over having plain HTML files. We are able to:
Display dynamic data sent from the server
Repeat over variables and lists
Template our applications
Let's work with the Instagram data in Node first in our server.js file. Once we have the Instagram data that
we need, we'll move over to our view files to display it.
package.json
Once your new folder is created, jump into the command line and start your Node application using:
$ npm init
Fill in your information however you like and then we'll install the packages that we need.
$ npm install express ejs instagram-node --save
This will install these three packages into the node_modules/ folder and add them to the dependencies
section of package.json .
server.js
We will now start up our server.js file. The main things we need to do in this file are:
Grab the packages we need (Express, EJS, instagram-node)
Configure these packages
Set Instagram API key
Set EJS as our templating engine
Set Express assets directory (for CSS)
Create a route for the home page
Grab Instagram popular images
Pass to our views
We have grabbed our packages, set the configurations that we need to, created one home page route, and
started our server. This can be done quickly in Node since we have the ability to app.use() and
View Files
Before we can test this server to make sure that everything is working, we'll need a view file to show! We're
going to move quickly through the view files since these aren't the main focus of our Node application.
views/partials/head.ejs
<meta charset="UTF-8">
<title>My First Node App!</title>
<!-- CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.2/cosmo/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
We're grabbing Bootstrap (http://getbootstrap.com/) from a CDN (http://bootstrapcdn.com/) for quick styling.
We picked one of the Bootstrap files from the Bootswatch (http://bootstrapcdn.com/#bootswatch_tab) section
of the site to switch up from the default Bootstrap styling.
We are also loading a stylesheet css/style.css . It is in our public/css/ folder, and since we set
express.static() in server.js , our application will serve assets from the public/ folder.
views/partials/header.ejs
Nothing too crazy here. Just a Bootstrap navbar with a link back to the home page. The span is one of the
Bootstrap glyphicons (http://getbootstrap.com/components/#glyphicons).
views/partials/footer.ejs
Good old copyright all the way back from the 1800s to the future!
views/pages/index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<% include ../partials/head %>
</head>
<body class="container">
<header>
<% include ../partials/header %>
</header>
<main>
instagram photos will go here
</main>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
We are using include to pull in the partials. This helps our application grab the other ejs files. In ejs, the <%
and %> tags will be how we display information.
public/css/style.css
body
{
padding-top:50px;
}
footer {
padding:50px;
}
This is all we'll add for styling right now. We'll style our images after we get them into our application.
With all that out of the way, let's start our server and view what we've created in our browser:
$ nodemon server.js
Next, we'll use the instagram-node package to get popular photos and display that in our app.
After we go through and create our client, we'll be given a client_id and client_secret.
This is exactly what we'll need to gain access to the Instagram API through our Node application.
If we click on the media/popular call and add client_id credentials to the URL like so:
https://api.instagram.com/v1/media/popular?client_id=e0e51c60672c4f09abe28c46c71a3a7a
We will be able to see the API return the important images.
On closer inspection, we can see we get an array of the images called data .
If we take a look at a single object in the data array, we can see that it is one photo with all the information that
we need.
We can grab the comments , likes , images , and user info. We're going to use these when building out
our application. We have what we need here:
client_id
client_secret
An understanding of the API data
Let's move forward and get this data into our application and showing to our users.
aren't being bombarded with ads, spam, or fake users. This helps keep the community at a higher level of
conduct.
Well if we can't replicate the website or its applications, what's the point in working with their API? That is a
good question. While Instagram seems to be pretty lenient on that rule since there are sites and apps that
pretty closely replicate the core apps features, there are also very neat applications like printstagram
(http://printstagr.am/), that will allow you to print out square sized images of your grams.
Instagram-Node
Back in our application, we will need to configure the instagram-node. Let's add this line in our configuration
section of our server.js file:
// CONFIGURE THE APP
// ==================================================
...
// configure instagram app with client_id
ig.use({
client_id: 'e0e51c60672c4f09abe28c46c71a3a7a',
client_secret: 'db11c575a8ae4f1aa90a03ba1d1345d8'
});
...
We've filled in our client credentials, but feel free to pass in your client's data. The instagram-node package
will handle the rest. We don't have to worry about appending our client_id to any URL like we did in the
API explorer.
The package also wraps a lot of the API calls to make them easier to use. The list of the API calls can be
found on their docs page (https://github.com/totemstech/instagram-node#using-the-api). The call that we want
is for the popular media. That call is:
ig.media_popular(function(err, medias, remaining, limit) {});
Using ejs in our view, we would be able to display the message variable by using:
<% message %>
app.get('/'... route.
Grab Instagram Data in Node
In server.js where we defined our main home page route, we will replace that entire route with:
// home page route - popular images
app.get('/', function(req, res) {
// use the instagram package to get popular media
ig.media_popular(function(err, medias, remaining, limit) {
// render the home page and pass in the popular images
res.render('pages/index', { grams: medias });
});
});
When we use the ig.media_popular() call, we gain access to the medias object. This contains all of the
We have created a link to the image on Instagram. We also have an instagram-bar to display the number
of likes and comments.
By looping over the grams object, we have access to everything that was returned by the API. You can use
the API explorer to look through the data and call the necessary items.
For the image, we are using images.standard_resolution.url and for likes and comments
respectively, we can use likes.count and comments.count .
If we wanted information about the user, we could use user.username and user.profile_picture . The
caption can be grabbed using caption.text .
Last step is to style up our images. Add the following to your style.css file:
.instagram-pic
{
position:relative;
padding:10px;
overflow:hidden;
}
.instagram-pic img {
padding:5px;
border-radius:2px;
box-shadow:0 0 5px rgba(0, 0, 0, 0.5);
}
.instagram-bar
{
position:absolute;
bottom:30px;
width:100%;
left:0;
padding-left:30px;
padding-right:30px;
color:#FFF;
}
.instagram-bar span {
margin-right:5px;
}
.instagram-bar .likes {
float:left;
}
.instagram-bar .comments {
float:right;
}
Conclusion
To recap, we've learned a bit about how Node works and why it's so neat. We've also been able to:
Process a JS file with Node
Install packages using npm
Create an HTTP server with Node and Express
Used a package to grab API data
Templated an application with EJS
Displayed data with EJS
The concepts here can apply to many different types of applications. Play around with the many packages
available on npm. The possibilities of what can be done with Node are endless.
You can pair it with a frontend framework like Angular (https://angularjs.org/) and a database system like
MongoDB (http://www.mongodb.org/) to create a MEAN Stack application. For more information on that,
check out the scotch.io book: MEAN Machine (https://leanpub.com/mean-machine).
For more Node and JavaScript tutorials, be sure to check out scotch.io (https://scotch.io) as we update
weekly with new articles and video courses.