0% found this document useful (0 votes)
2 views

NODE.JS

The document provides a comprehensive guide on creating a web server using Node.js, emphasizing the use of modules like HTTP, URL, and fs for handling requests and serving files. It introduces Express as a framework to simplify server code and discusses the integration of MongoDB for database management. Additionally, it covers the installation of Node.js and Express, basic server setup, serving static content, and using handlebars.js for templating in a JavaScript ecosystem.

Uploaded by

oluebubee574
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

NODE.JS

The document provides a comprehensive guide on creating a web server using Node.js, emphasizing the use of modules like HTTP, URL, and fs for handling requests and serving files. It introduces Express as a framework to simplify server code and discusses the integration of MongoDB for database management. Additionally, it covers the installation of Node.js and Express, basic server setup, serving static content, and using handlebars.js for templating in a JavaScript ecosystem.

Uploaded by

oluebubee574
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Node.

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');

It will have to be installed if it is not yet present, using the command:


npm install Or you can also

use: npm -g install

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');

2. Next, in a subfolder public, we create hello.html:


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello world document</title>
<link href="./styles/hello.css" rel="stylesheet">
</head>
<body>
<h1>Hello, World</h1>
</body>
</html>

3. We can create the background with hello.css as follows:


body {
background-color:#FFDEAD;
} h1 { color:teal; margin-
left:30px;
}
.bigbutton { height:40px; color:
white; background-color:teal;
margin-left:150px; margin-top:50px;
padding:15 15 25 15; font-
size:18px;
}
So if we now visit http://localhost:8080/hello.html, we will see our by now too familiar
Hello World message with some basic styling, proving that our file server also delivered
the CSS file.
1. Now we will take it one step further by actually adding JavaScript to our html
file (hellobutton.html (body only)). We will reuse the previous CSS file, create
a slightly different HTML file, and add a JavaScript file. I assume you have a
copy of jQuery around somewhere.
<body>
<div id="content">
<button type="button" id="hellobutton" class="bigbutton">Click here for a
message</button>
</div>
<script src="js/jquery.js"></script>
<script src="js/hellobutton.js"></script>
</body>

2. To add the button, let's create hellobutton.js:


$(document).ready(function(){
$("#content").on("click", "#hellobutton", function(data){
$('#hellobutton').text("Hello World");
} );
});

So when we go to http://localhost:8080/hellobutton.html, we see a web page with a


button; when we click on it, its text changes into Hello World. This means our client-side
jQuery and JavaScript works.
In the public folder, create a file index.html:
<!DOCTYPE html >
<html>
<body>
<h1>It works!</h1>
</body>
</html>

If we go to http://localhost:8080, we see It Works ! Just like when we hit the document


root of the Apache Web Server. This is because our node-static module has that file
configured as the default.
But there are other things that do not work the way we are used to. If we type
hellobutton instead of hellobutton.html, nothing will happen, as we did not program
our web server to look for hellobutton.something. Don't even think of wanting to
process hello.html?key=value.

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

Or you can also use:


npm install —save 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.

Our first Express app


Of course, we are going to do more Hello, World examples. Here is our first Express
app:
var express = require('express'); var app =
express();
app.set('port', process.env.PORT || 3000); app.get('/', function
(req, res) { res.send('<h1>Hello World!</h1>');

});
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).

An example with middleware


We will now use Express to rewrite the hello button example. All static resources in
the public directory can remain untouched. The only change is in the node app itself:
var express = require('express'); var path =
require('path'); var app = express(); app.set('port',
process.env.PORT || 3000);
var options = { dotfiles: 'ignore',
extensions: ['htm', 'html'], index: false
};

app.use(express.static(path.join(__dirname, 'public') ,

options )); app.listen(app.get('port'), function ()

{ console.log('Hello express started on http://localhost:' +

app.get('port') + '; press Ctrl-C to terminate.' );

});

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.

Templating and handlebars.js


There is one more Hello, world example to go! Throughout the book, we have been
using PHP most of the time. We have used it to dynamically generate web pages, or
portions thereof. So PHP code, often embedded inside HTML code in a file with .php as
an extension, is executed on the server and what is rendered by the browser is pure
HTML. You also learned how to generate HTML from a separate PHP file or even
JavaScript on the client side, using data that comes from the server, and then inject it
into a portion of a web page (Ajax).
Combining PHP and HTML and even a small chunk of client-side JavaScript inside a
single file was made possible thanks to the <script> tag and by putting PHP code in
between <?php and ?>. That is why they sometimes call PHP a templating language.
Now imagine an all-JavaScript ecosystem. Yes, we could still put our client JavaScript
code in between <script> tags, but what about the server JavaScript code? There is no
such thing as <?javascript ?> because this is not how node.js works.
Node.js and Express support several templating languages that allow you to separate
layout and content and have the template system do the work to go fetch the content
and inject it into the HTML. As we no longer want to learn yet another language, we
decided to go with handlebars.js, as it uses plain HTML to define your layout, that
you already learned some 12 chapters ago. The default templating language for
Express appears to be Jade, which uses its own, albeit more compact, because there
are no tags, format. Another advantage of using handlebars.js is that is also available
to do client-side templating.
We conclude this chapter with an example of how you could use handlebars.js.
Our examples in this chapter are all node.js examples, for which we need modules. To
use handlebars in node and Express, there are several modules available. I like the
one with the easy to remember name express-handlebars. If you search the web for
handlebars.js, you will find the library to do client-side templating.
Get the handlebars module for Express using the following command:
npm install express-handlebars

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>

Our last Hello, World example


Now create a file lasthello.js in the project folder. For convenience, we added the
relevant code to the previous Express example. Everything that worked before still
works but if you type http://localhost:3000/, you will see a page with the layout from
the layout file and {{{body}}} replaced by(you guessed it):
var express = require('express'); var path =
require('path'); var app = express();
var handlebars = require('express-handlebars') .create({ defaultLayout:'main' });
app.engine('handlebars', handlebars.engine); app.set('view
engine', 'handlebars'); app.set('port', process.env.PORT || 3000);

var options = { dotfiles: 'ignore',


etag: false, extensions: ['htm', 'html'],
index: false };

app.use(express.static(path.join(__dirname, 'public') , options )); app.get('/',


function(req, res)
{
res.render('hello'); // this is the important part
});
app.listen(app.get('port'), function () {
console.log('Hello express started on http://localhost:' + app.get('port') + ';
press Ctrl-C to terminate.' );

You might also like