티스토리 뷰

오늘은 nodejs의  express라는 web framework에 대해 알아보도록 하겠습니다.


설치환경

OS ubuntu 12.10

nodejs v0.8.15

npm 1.1.66


step 1. express 설치

$ npm install express -g

  

※주의사항

express가 동작을 안하는 경우가 생겨 확인해 보았더니 nodejs 버전이 0.6때 로 설치가 되어 재설치 하였습니다.

참고하시기 바랍니다.

sudo apt-get install python-software-properties

sudo add-apt-repository ppa:chris-lea/node.js

sudo apt-get update

sudo apt-get install nodejs npm


또한 중간중간 이러한 오류도 발견되는 경우가 있습니다.

이럴경우에도 아래와 같이 처리해 주시기 바랍니다.

.

.

.

npm http 200 https://registry.npmjs.org/cookie/-/cookie-0.0.5.tgz

npm http 200 https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.1.1.tgz

npm http 200 https://registry.npmjs.org/methods/-/methods-0.0.1.tgz

npm WARN package.json methods@0.0.1 No README.md file found!

npm http 200 https://registry.npmjs.org/cookie-signature/-/cookie-signature-0.0.1.tgz

npm http 200 https://registry.npmjs.org/send/-/send-0.1.0.tgz

npm http 200 https://registry.npmjs.org/debug/-/debug-0.7.0.tgz

npm http 200 https://registry.npmjs.org/connect/2.7.1

npm http GET https://registry.npmjs.org/connect/-/connect-2.7.1.tgz

.
.
.

$ sudo npm cache clean



step 2. express web project 생성

  $ cd ~/work

  $ mkdir blog
  $ cd blog
  $ express -c stylus   # 해당 스타일 적용
  $ npm install -d  # 해당 Project Dependency download


Project  생성 구조

express                   /* The top level folder containing our app  */
|-- app.js                /* The application code itself              */
|-- lib                      /* Third-party dependencies                 */
|-- public                /* Publicly accessible resources            */
|   |-- images
|   `-- javascripts
|   `-- stylesheets 
`-- views                 /* The templates for the 'views'            */


step 3. 간단 메모리 blog 예제
jade라는 Template Engine을 이용하여 간단 블로그 리스트를 구현

blogapp.js
var express = require('express');
var ArticleProvider = require('./articleprovider-memory').ArticleProvider;

var app = module.exports = express();

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(require('stylus').middleware({ src: __dirname + '/public' }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

var articleProvider= new ArticleProvider();

app.get('/', function(req, res){
    articleProvider.findAll( function(error,docs){
        res.render('blog.jade', { locals: {
            title: 'Blog',
            articles:docs
            }
        });
    })
});

app.listen(3000);

articleprovider-memory.js
var articleCounter = 1;

ArticleProvider = function(){};
ArticleProvider.prototype.dummyData = [];

ArticleProvider.prototype.findAll = function(callback) {
  callback( null, this.dummyData )
};

ArticleProvider.prototype.findById = function(id, callback) {
  var result = null;
  for(var i =0;i<this.dummyData.length;i++) {
    if( this.dummyData[i]._id == id ) {
      result = this.dummyData[i];
      break;
    }
  }
  callback(null, result);
};

ArticleProvider.prototype.save = function(articles, callback) {
  var article = null;

  if( typeof(articles.length)=="undefined")
    articles = [articles];

  for( var i =0;i< articles.length;i++ ) {
    article = articles[i];
    article._id = articleCounter++;
    article.created_at = new Date();

    if( article.comments === undefined )
      article.comments = [];

    for(var j =0;j< article.comments.length; j++) {
      article.comments[j].created_at = new Date();
    }
    this.dummyData[this.dummyData.length]= article;
  }
  callback(null, articles);
};

/* Lets bootstrap with dummy data */
new ArticleProvider().save([
  {title: 'Post one', body: 'Body one', comments:[{author:'Bob', comment:'I love it'}, {author:'Dave', comment:'This is rubbish!'}]},
  {title: 'Post two', body: 'Body two'},
  {title: 'Post three', body: 'Body three'}
], function(error, articles){});

exports.ArticleProvider = ArticleProvider;


view/blog.jade
extends layout

block content
  h1= locals.title
  #articles
    - each article in locals.articles
      div.article
        div.created_at= article.created_at
        div.title
            a(href="/blog/"+article._id)!= article.title
        div.body= article.body


$ node blogapp.js


[ 그림1 ] 결과화면













'Developer' 카테고리의 다른 글

chrome browser 설치하기  (0) 2012.12.20
[ java ] oracle connection pool 설정  (0) 2012.12.14
resolve.conf DNS 초기화 문제  (0) 2012.12.06
ANSI Code 적용하여 컬러풀한 출력하기.  (0) 2012.12.05
[github] github 사용법.  (3) 2012.11.27
댓글