NODE.JS
NODE.JS
js
Let's recapitulate a bit;The World Wide Web, I learned about the World Wide Web
and how all these millions of pages are accessed by people using a browser that
sends requests to a web server using the HTTP protocol. Well, people will still use
browsers that send HTTP requests, but we just tossed the web server, now what do
we do? We write one. Scary? No, it will be a lot of fun. Writing low-level code is not
your thing? No sweat, somebody already did it for you. There is a whole community
writing code for node.js that everybody else can use. That code is made available as
what is referred to as modules, and of course there is a HTTP module available to
us.
Another thing the web server did for us was to actually analyze the URL the user typed
and explore the file system to see whether there is a physical file, for example, an
hello.html file, and serve it up back to the client. We will have to write that too. This is
cool because it will give us full control over what exactly our web server should be able
to handle and what it shouldn't. As expected, there are url and fs modules for node.js
as well.
We will need a database but, we already know one that we like: MongoDB. Can we use
it with node.js? Yes we can. There is a module or driver for it to access the existing
MongoDB server from node.js. As MongoDB is a document database and documents
are really JSON objects, this is a perfect fit in an all-JavaScript ecosystem.
Little by little we are beginning to realize, before even having written one, whether a
node application is actually going to be a web server that contains application-specific
code or an application that contains a web server; take your pick.
As soon as I walk you through our first examples, you will realize that we never before
had a need to write so much code for a simple Hello, World program. Imagine having
to write a fully-featured single page web application with so much low-level code? This
is where Express fits in. It is a framework for node.js that will help us write cleaner,
more compact code. This is our jQuery on the server side. As soon as our examples
become too boringly long, we will switch to Express.
There is another thing we tossed: Apache as an Application Server, the part that
gave us PHP as a language on the server. We have been generating HTML
dynamically on the server using PHP and, by the time the browser read it, it had
become all HTML.
The nice part of using PHP was that we could embed PHP code inside plain HTML in
between <?php and ?>. Stuffing an HTML file with <script> tags to include
JavaScript code is not very appealing. We will look at a solution for that as well.
Installing node.js
Let's not delay any further and install node on your computer. How to install it will be
different depending on the OS you are running. Go to http://nodejs.org/ and get the
proper download. The result is the same everywhere: it gives us two programs: node
and npm.
npm
npm, the node packaging manager, is the tool that you use to look for and install
modules. Each time you write code that needs a module, you specify this by putting
something like the following in your code: var module = require('module');
The latter will attempt to install the module globally, the former command in the
directory where the command is issued. It will typically install the module in a folder
called node_modules.
node
The node command is the command to use to start your node.js program, for example:
node myprogram.js
Node will start and interpret your code. Type Ctrl + C to stop node. Let's get to our first
programs right away.
Our inevitable Hello, world example is the smallest possible web server:
var http = require('http'); http.createServer(function (req, res)
{ res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n'); }).listen(8080, 'localhost');
console.log('Server running at http://localhost:8080');
Save this file as hello.js, or get it from the Packt Publishing website and, in a terminal
window, type:
node hello.js
This command will run the program using node. In the terminal window, which becomes
your console, you will see the text Server running.
Next, when you start a browser and type in http://localhost:8080 as the URL,
something that looks like a web page, containing the famous two-word sentence
Hello World, will appear. As a matter of fact, if you go to http://
localhost:8080/it/does/not/matterwhat, the same thing will appear. Not very
useful maybe, but it is a web server.
Adding HTML
This is a slightly different version where we explicitly specify that we send HTML instead
of plain text:
var http = require('http'); http.createServer(function (req, res)
{ res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello World\</h1>');
}).listen(8080, 'localhost'); console.log('Server running at
http://localhost:8080');
Serving up static content
We are not used to the same thing popping up no matter what path we give as an URL.
URLs typically point to a file (or a folder, in which case the server looks for an
index.html file), foo.html or bar.php, and, when present, it is served up to the client.
So what if we want to do this with node.js? We need a module. There are several ways
to do the job. We use node-static in our example. First we need to install it: npm
install node-static
You can typically find documentation on methods and properties on Github and other
cool places. In our app, we create not only a web server but a fileserver as well. It will
serve all the files in the local directory public. It is good to have all so called static
content together in a separate folder. This is basically all the files that will be served up
to and interpreted by the client. As we will now end up with a mix of client code and
server code, it is good practice to separate them. When you use the Express framework,
it will create these things for you.
1. In our project folder we create hello.js, our node.js app:
var http = require('http'); var static = require('node-static'); var
fileServer = new static.Server('./public');
http.createServer(function (req, res) { fileServer.serve(req,res);
}).listen(8080, 'localhost'); console.log('Server running at
http://localhost:8080');
On the other hand, if you put a picture file, for example, baywatchstation.jpg, in
./public and type http://localhost:8080/baywatchstation.jpg, you will see the picture
in your browser. All this is done with very few lines of code and two cool node.js
modules.
Installing Express
Of course, Express is also a node module, so we install it as such. At the time of writing,
we used Express 4. In your project directory for your application, type:
npm install express
If you specify the —save option, npm will update the package.json file. You will notice that
a folder called express will be created inside node_modules and inside that one there is
another collection of node-modules. These are examples of what is called middleware.
In the few examples that follow, we assume app.js as the name for your node.js
application and app for the variable that you will use in that file for your instance of
Express. This is for the sake of brevity. It would be better to use a string that matches
your project name.
});
app.listen(app.get('port'), function () { console.log('Express started on
http://localhost:' + app.get('port') + '; press Ctrl-C to terminate.' );
});
Well, compared to our second node.js example, it is about the same number of lines.
But it looks a lot cleaner and it does more for us. You no longer need to explicitly
include the HTTP module, you no longer have to specify which header to send, and,
when you specify a different URL, you will not get Hello, World but a reasonable error
message. We use app.set and app.get for the port. When the environment variable PORT
is set, the port will be set to its value.
The other line containing app.get tells us what we want to happen when the server is
presented with a URL in the GET mode. Like in node.js, there is a function with the
request and respond objects as an argument. In express, they have been extended;
there are more creative things you can do with them as there are more methods
available to you.
For example, you have access to req.body, which will contain an object of all the values
that were sent using the POST method in a form (using app.post).
app.use(express.static(path.join(__dirname, 'public') ,
});
This code uses so-called middleware (static) that is included with express. There is a
lot more available from third parties. In the req.body referenced earlier, there is
middleware available to parse that form data (body-parse). You can also write your own
middleware. In its simplest form, it is a function with req and res as its arguments:
app.use (function(req,res) { res.status(404);
res.send(" Oops, you have tried to reach a page that does not
exist"); });
This is your minimal 404 handler to give people something meaningful to read on their
screen when they type in the wrong URL. You place that in your app.js file after the
code that represents the successful scenarios.
Creating a layout
Inside your project folder that contains public, create a folder views, with a subdirectory
layouts. Copy other static content you may have from public to views. Inside the
layouts subfolder, create a file called main.handlebars. This is your default layout. Think
of it as a common layout for almost all of your pages:
<!doctype html>
<html>
<head>
<title>Handlebars demo</title> </head>
<link href="./styles/hello.css" rel="stylesheet">
<body>
{{{body}}}
</body>
</html>
Notice the {{{body}}} part. This token will be replaced by HTML. Create, in the views
folder, a file called hello.handlebars with the following content. This will be one (of
many) example of the HTML, and it will be replaced by:
<h1>Hello, World</h1>