博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Node.js and Express
阅读量:4031 次
发布时间:2019-05-24

本文共 8559 字,大约阅读时间需要 28 分钟。

Creating a basic site with Node.js and Express

A walkthrough on how to create and deploy a basic site with Node.js and the Express framework

Estimated reading time: 7 minutes

Table of contents

What we are going to do

This walkthrough will go over setting up a basic site using  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 , an excellent web framework for node created by  who seems to be pumping out Node.js libraries like he was ten men.

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

Setup

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

If you are on Linux there are plenty of .

For Windows users there are also  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:

node -vv0.8.21npm -v1.2.12

Create an Express site

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

First let’s install express

npm install -g express-generator

The -g flag means that you are installing express globally on your system.

Now we can create an express application.

express -c stylus express_example

The -c states that we want to use stylus for css. You should see the following output:

create : express_examplecreate : express_example/package.jsoncreate : express_example/app.jscreate : express_example/publiccreate : express_example/public/javascriptscreate : express_example/public/imagescreate : express_example/public/stylesheetscreate : express_example/public/stylesheets/style.stylcreate : express_example/routescreate : express_example/routes/index.jscreate : express_example/routes/user.jscreate : express_example/viewscreate : express_example/views/layout.jadecreate : express_example/views/index.jadeinstall dependencies: $ cd express_example && npm installrun the app: $ node app

As per the instructions you’ll need to install dependencies so do this

cd express_example && npm install

This will install packages and you will see a lot of output. When this is complete you can boot your application.

Boot the app

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

node app.js

With a recent express version this command has changed, so if the app doesn’t start you can try

npm start

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

Using Git

 is a version control system that is used heavily in the Node.js ecosystem, particulary with . If you aren’t familiar with Git  is your go-to man. He’s written extensively and eloquently on Git for beginners and experts. Checkout  for if you are a beginner and  for 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.

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  has solved this problem with . Nodemon will reload your application each time it changes so you don’t need to restart it. If you have used  for Ruby with  it is similar to that. To install run

npm install -g nodemon

Then you can start your app with

nodemon

Nodemon automatically looks in your project setting to find the appropriate files and setting to start your server. If this does not work try:

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 

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 . If you’ve used  it is similar to that. In the example we use jade to setup a layout template.

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 
felis eu leo aliquet
ac rutrum odio aliquet section.cell p Mauris porttitor
felis eu leo aliquet
ac rutrum odio aliquet section.cell p Mauris porttitor
felis eu leo aliquet
ac rutrum odio aliquet section.cell p Mauris porttitor
felis eu leo aliquet
ac rutrum odio aliquet

This is a common template we can reuse. The line section#wrapper!= bodypulls 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 .

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 . This is very similar to and supports variables, mixins, functions and more. I really like it! Here’s an example from our stylesheet

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 , allowing you to set up RESTful routes.

In this example we setup three routes in 

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  for more.

Publishing your site

We’ve now developed a basic Node.js site using express and we want to host it somewhere. Publishing the site to  is free and you can be up and running in no time. You can sign up for an account at  for free and then install the .

To make your example node site work with Heroku you must create a file called Procfile in the root of the project. Add the following.

web: node app.js

To make sure Heroku uses the correct versions of node add this to the package.json file

"engines": {  "node": "0.8.x",  "npm": "1.2.x"}

Then you can use the command line tools to create a site on Heroku and publish it.

heroku apps:create git push heroku master

Easy!

Some other Node.js hosting providers include , ,  and .

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  for a taste of what to expect.

If you find any inaccuracies in the post  and I’ll update the post.

Further reading

Tags

Recent Posts

  • Tutorial on using pwd, a UNIX and Linux command for printing the name of the current working directory. Examples of printing the current working directory, avoiding symlinks and how to get the current working directory in shell scripts.

  • Example of how to setup Cloudfront to log to S3, enable log rotation and how to download and work with combined Cloudfront log files.

  • Tutorial on using df, a UNIX and Linux command for reporting file system disk space usage. Examples of viewing free disk space, viewing in human readable format, showing filesystem types and including and excluding specific filesystem types.

About the author

Picture of George Ornbo

George Ornbo is co-founder and Managing Director of .

He is the author of . He can be found in most of the usual places as shapeshed including  and .

转载地址:http://cuebi.baihongyu.com/

你可能感兴趣的文章
1.3 Debugging of Shaders (调试着色器)
查看>>
关于phpcms中模块_tag.class.php中的pc_tag()方法的含义
查看>>
vsftp 配置具有匿名登录也有系统用户登录,系统用户有管理权限,匿名只有下载权限。
查看>>
linux安装usb wifi接收器
查看>>
关于共享单车定位不准问题
查看>>
终于搞定CString和string之间转换的问题了
查看>>
用防火墙自动拦截攻击IP
查看>>
补充自动屏蔽攻击ip
查看>>
谷歌走了
查看>>
多线程使用随机函数需要注意的一点
查看>>
getpeername,getsockname
查看>>
让我做你的下一行Code
查看>>
浅析:setsockopt()改善程序的健壮性
查看>>
关于对象赋值及返回临时对象过程中的构造与析构
查看>>
VS 2005 CRT函数的安全性增强版本
查看>>
SQL 多表联合查询
查看>>
Visual Studio 2010:C++0x新特性
查看>>
drwtsn32.exe和adplus.vbs进行dump文件抓取
查看>>
cppcheck c++静态代码检查
查看>>
CLOSE_WAIT和TIME_WAIT
查看>>