Creating a Basic Site With node.js and ExpresS

来源:互联网 发布:起名字的软件 编辑:程序博客网 时间:2024/05/03 00:11

What we are going to do

This walkthrough will go over setting up a basic site using node.js and Express. The walkthrough is aimed at beginners exploring node.js as I’ve had many questions from friends and colleagues about creating and deploying node apps. If you are not a beginner the article probably won’t be of much use to you. We are going to use express, an excellent web framework for node created by TJ Holowaychuk who seems to be pumping out node.js libraries like he was ten men.

Here is the site we are going to create. You might also want to grab the source code.

Example Express website

Setup

First we need to setup our development environment. If you are on OSX I’ve covered how to setup node.js and npm on OSX in a previous article. If you haven’t got everything installed follow that article.

If you are on Linux there are plenty of articles on Google.

For Windows users there are also resources on Google but it is a bit more tricky.

Prerequisites

If everything has installed ok you should now have node.js and npm running on your machine. At the terminal type node -v and npm -v and you should see something like:

1234
node -vv0.4.5npm -v1.0.1rc7

You’ll see I’m using the RC of version 1 of npm. I encourage you to install this as this will soon become the default.

Create an Express site

Still with me? We’ve covered a lot already! Now let’s create an Express site.

First let’s create a folder for our project and install Express.

123
mkdir express_examplecd express_examplenpm install express

This installs Express into the directory we created. Now we can create the skeleton site. We are going to use jade and stylus for templating and css. More on those later.

1234567891011121314151617
./node_modules/express/bin/express -t jade -c stylusdestination is not empty, continue? y   create : .   create : ./app.js   create : ./public/stylesheets   create : ./public/stylesheets/style.styl   create : ./public/images   create : ./public/javascripts   create : ./logs   create : ./pids   create : ./test   create : ./test/app.test.js   create : ./views   create : ./views/layout.jade   create : ./views/index.jade   - make sure you have installed stylus: $ npm install stylus   - make sure you have installed jade: $ npm install jade

You’ll see that we need to install a couple of dependencies for stylus and jade support so let’s do that.

1
npm install stylus jade

Boot the app

That’s all the setup you need. Phew. Now you can boot the app:

1
node app.js

You should see Express server listening on port 3000 and if you open http://0.0.0.0:3000 you’ll see the default Express page.

Using Git

Git is a version control system that is used heavily in the node.js ecosystem, particulary with Github. If you aren’t familiar with Git Scott Chacon is your go-to man. He’s written extensively and eloquently on Git for beginners and experts. Checkout Gitcasts for if you are a beginner and ProGitfor more advanced stuff. We are going to use git to version our site and publish it so let’s set up our repo now. If your Express server is still running hit CTRL + C to stop it.

123
git initgit add .git commit -m 'initial commit'

Developing node.js sites

Normally when you develop a node.js site you’ll need ot restart your application each time you make a change. Thankfully our home-grown British JavaScript genius Remy Sharp has solved this problem with nodemon. Nodemon will reload your application each time it changes so you don’t need to restart it. If you have used Shotgun for Ruby with Sinatra it is similar to that. To install run

1
npm install -g nodemon

Then you can start your app with

1
nodemon app.js

Using nodemon means you don’t have to restart your app each time you make a change. For more infomation on nodemon see the README

HTML in Express

Express is agnostic as to which templating language you use. Templating languages can be a hot topic of debate but for this article I’m going to use jade. If you’ve used haml it is similar to that. In the example we use jade to setup a layout template.

12345678910111213141516171819202122232425262728
!!! 5html  head    title= title    link(rel='stylesheet', href='/stylesheets/style.css')    link(rel='stylesheet', href='/stylesheets/chunkfive-fontface.css')  body    header      nav        ul          li            a(href="/") Home          li            a(href="/about") About          li            a(href="/contact") Contact    section#wrapper!= body        footer          section.css-table            section.four-column              section.cell                p Mauris porttitor <br />felis eu leo aliquet<br /> ac rutrum odio aliquet              section.cell                p Mauris porttitor <br />felis eu leo aliquet<br /> ac rutrum odio aliquet              section.cell                p Mauris porttitor <br />felis eu leo aliquet<br /> ac rutrum odio aliquet              section.cell                p Mauris porttitor <br />felis eu leo aliquet<br /> ac rutrum odio aliquet

This is a common template we can reuse. The line section#wrapper!= body pulls in content from the page it is used on. Express also supports variables that you pass through to the template. In this case we pass the title variable. If you are coming from Sinatra this will all be familiar to you. If you are not I recommend consulting the Express documentation.

CSS in Express

Again Express is agnostic to what you use to generate your CSS - you can use vanilla CSS but for this example I’m using Stylus. This is very similar to Sass and supports variables, mixins, functions and more. I really like it! Here’s an example from our stylesheet

12345678910111213
body  font 62.5%/1.5  Helvetica, Arial, "Lucida Grande", "Lucida Sans", Tahoma, Verdana, sans-serif  text-align center  background #000#wrapper  width 920px  text-align left  margin-left auto  margin-right auto  background #fff  padding 20px  border-bottom-radius(15px)

You’ll see that stylus is very terse - you don’t need brackets or commas.

Routing in Express

Routing is similar to Sinatra, allowing you to set up RESTful routes.

In this example we setup three routes in app.js

1234567891011121314151617
app.get('/', function(req, res){  res.render('index', {    title: 'Home'  });});app.get('/about', function(req, res){  res.render('about', {    title: 'About'  });});app.get('/contact', function(req, res){  res.render('contact', {    title: 'Contact'  });});

See the Express documentation for more.

Publishing your site

We’ve now developed a basic node.js site using express and we want to host it somewhere.

There are a number of hosting options for node. It isn’t so difficult to host it yourself but for me the easiest and best is Nodester. If you have used Heroku the deployment process is very similar. You’ll need to request an invite for Nodester (it won’t come through immediately though).

1
curl -X POST -d "email=your_address@gmail.com" http://nodester.com/coupon

Chris Matthieu has created a handy video going over how to deploy to Nodester so go and watch that if you don’t fancy reading the documentation.

Let’s create the site on nodester

1
nodester app create express_example app.js

Now we can get the information on the site

12345
nodester app info express_examplenodester info Gathering information about: express_examplenodester warn express_example on port 9451 running: false (pid: unknown)nodester info gitrepo: ec2-user@nodester.com:/node/hosted_apps/shapeshed/1298-ec0117a54b696d7a9781c79e5283692e.gitnodester info appfile: app.js

To publish the site we need to add the git repo as a remote our git repo

1
git remote add nodester ec2-user@nodester.com:/node/hosted_apps/shapeshed/1298-ec0117a54b696d7a9781c79e5283692e.git

And finally we can publish the site by pushing

1
git push nodester master

Nodester will let you know about the deploy - if the deploy was successful you can see your app at http://[your_app_name].nodester.com/. In this example you can see the site at http://express_example.nodester.com

Some other node.js hosting providers include nodejitsu, Joyent, Cloud Foundry and Duostack.

Conclusion

This article has showed how to create a very basic site using node.js and Express. It has introduced a number of things from the node.js ecosystem and showed you how to deploy your app to Nodester.

The strengths of node.js as a technology are not so much in building static websites like this. I encourage you to explore some of the node.js libraries to see what it can do. Particularly for real-time applications node.js is extremely exciting and I think we’ll see some great apps built on node.js. Try starting with socket.io for a taste of what to expect.

If you find any inaccuracies in the post send me an email and I’ll update the post.

Further reading

  • node.js
  • express - node web framework
  • npm - node package manager
  • jade - node.js templating language
  • stylus - node.js css framework
  • Setting up node.js and npm on Mac OSX
  • Nodester - Open Source Hosting for node.js
  • Source code for this article
转自:http://shapeshed.com/creating-a-basic-site-with-node-and-express/
原创粉丝点击