A Simple Web Server With Node
A Simple Web Server With Node
Routing
Routing refers to the mechanism for serving the client the content it has
asked for.
http.createServer(function(req,res){
// normalize url by removing querystring, optional
// trailing slash, and making lowercase
var path = req.url.replace(/\/?(?:\?.*)?$/, '') .toLowerCase();
switch(path) {
case '':
serveStaticFile(res, '/public/home.html', 'text/html');
break;
case '/about':
serveStaticFile(res, '/public/about.html', 'text/html');
break;
case '/img/logo.jpg':
serveStaticFile(res, '/public/img/logo.jpg', 'image/jpeg');
break;
default:
serveStaticFile(res, '/public/404.html', 'text/html',
404);
break;
}
}).listen(3000);
console.log('Server started on localhost:3000; press Ctrl-C to
terminate....');
Initial Steps :
Start by creating a new directory for your project: this will be
the root directory for your project.
npm manages project dependencies—as well as metadata
about the project—in a file called package.json. The easiest
way to create this file is to run npm init: it will ask you a series
of questions and generate a package.json file to get you started
(for the “entry point” question, use meadowlark.js or the name
of your project).
Create a project directory called website
E:\nodeapps>md website
E:\nodeapps>cd website
E:\nodeapps\website>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess
sensible defaults.
See `npm help json` for definitive documentation on these
fields and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (website)
version: (1.0.0)
description:
entry point: (index.js) app.js
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to E:\nodeapps\website\package.json:
{
"name": "website",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes) yes
The first step will be installing Express. Run the following npm
command:
npm install --save express
Running npm install will install the named package(s) in the
node_modules directory. If you specify the --save flag, it will
update the package.json file. Since the node_modules dirctory
can be regenerated at any time with npm, we will not save it in
our repository. To ensure we don’t accidentally add it to our
repository, we create a file called .gitignore: # ignore packages
installed by npm
node_modules # put any other files you don't want to check in
here, # such as .DS_Store (OSX), *.bak, etc.
Now create a file called app.js. This will be our project’s entry
point
Now that we’ve got some views set up, we have to replace our old routes with new
routes
res.render('home');
});
res.render('about');
});
res.status(404);
res.render('404');
});
console.error(err.stack);
res.status(500);
res.render('500');
});
Note that we no longer have to specify the content type or status code: the view engine
will return a content type of text/html and a status code of 200 by default. In the catch
all handler, which provides our custom 404 page, and the 500 handler, we have to set
var fortunes = [
"Conquer your fears or they will conquer you.",
"Rivers need springs.",
"Do not fear what you don't know.",
"You will have a pleasant surprise.",
"Whenever possible, keep it simple.",
];
Modify the view (/views/about.handlebars) to display a fortune:
var randomFortune =
fortunes[Math.floor(Math.random() * fortunes.length)];
});
Initial Steps | 27Now if you restart the server and load the /about
page
Handlebars Basics
The key to understanding templating is understanding the concept of context. When
you render a template, you pass the templating engine an object called the context ob‐
want to pass HTML to the template? For example, if our context was instead { name:
solve this problem, simply use three curly brackets instead of two: {{{name}}}.
Comments
Comments in Handlebars look like {{! comment goes here }}. It’s important to un‐
derstand the distinction between Handlebars comments and HTML comments. Con‐
Assuming this is a server-side template, the super-secret comment will never be sent to
the browser, whereas the not-so-secret comment will be visible if the user inspects the
HTML source. You should prefer Handlebars comments for anything that exposes im‐
Express:
app.engine('handlebars', handlebars.engine);
view—essentially, a template for templates. Layouts are essential because most (if not
all) of the pages on your site will have an almost identical layout. For example, they
must
have an <html> element and a <title> element, they usually all load the same CSS files,
and so on. You don’t want to have to duplicate that code for every single page, which is