Creating a Basic Site With node.js and ExpresS

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:

1
2
3
4
node -v
v0.4.5
npm -v
1.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.

1
2
3
mkdir express_example
cd express_example
npm 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
./node_modules/express/bin/express -t jade -c stylus
destination 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.

1
2
3
git init
git 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
!!! 5
html
  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

1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

1
2
3
4
5
nodester app info express_example
nodester info Gathering information about: express_example
nodester warn express_example on port 9451 running: false (pid: unknown)
nodester info gitrepo: ec2-user@nodester.com:/node/hosted_apps/shapeshed/1298-ec0117a54b696d7a9781c79e5283692e.git
nodester 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 nodejitsuJoyentCloud 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值