블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2017. 4. 4. 10:59 Dev Environment/Build System

Gulp 빌드 환경에 파일이 변경되었을 때 자동으로 브라우져 화면을 업데이트해주는 Live reload환경을 접목해 본다.





Gulp 환경 만들기


gulp CLI를 설치한다.

$ npm i -g gulp-cli


npm 대신 속도가 빠르다는 yarn을 사용해 본다. yarn을 설치한다.

$ npm i -g yarn



테스트 폴를 생성하고,yarn을 이용해 package.json을 만든다. -y 플래그를 주면 모두 Yes로 응답해서 package.json을 생성해준다.

$ mkdir livereload && cd livereload

$ yarn init -y

yarn init v0.21.3

warning The yes flag has been set. This will automatically answer yes to all questions which may have security implications.

success Saved package.json

✨  Done in 0.06s.



index.html파일을 생성하고, gulp 패키지를 로컬에 설치한다. index.html에 간단한 body 태그를 넣는다. 

$ touch index.html

$ yarn add --dev gulp


TypeScript기반으로 파일을 작성하기 위해 다음 설정을 한다. [Typescript] NodeJS에서 Typescript 사용하기

$ yarn add --dev @types/node



gulp환경파일을 생성하고, default 태스크를 작성한다. gulp 명령을 실행하면 default 태스크가 실행된다.

$ touch Gulpfile.ts


// Gulpfile.js

const gulp = require('gulp');


gulp.task('default', function () {

  console.log('Gulp and running!')

});


// test

$ gulp

[09:27:23] Using gulpfile ~/prototyping/livereload/gulpfile.ts

[09:27:23] Starting 'default'...

Gulp and running!

[09:27:23] Finished 'default' after 71 μs





테스트 서버 환경 만들기


Express를 설치하고 정적 파일을 처리하는 서버를 생성한다.

$ yarn add --dev express


// Gulpfile.ts

const gulp = require('gulp');


function startExpress() {

  const express = require('express');

  const app = express();

  app.use(express.static(__dirname));

  app.listen(4000);

}


gulp.task('default', () => startExpress());


index.html 을 작성하고, gulp 명령을 수행한 다음 http://localhost:4000 호출해서 hi peter가 출력하면 정상작동이다. 

<!DOCTYPE html>

<html>

  <head>

    <meta charset="utf-8">

    <title></title>

  </head>

  <body>

    hi peter

  </body>

</html>


다음으로 livereload server 인 tiny-lr을 설치한다.

$ yarn add --dev tiny-lr


tiny-lr서버도 gulp환경에 넣는다. gulp명령을 실행하고 http://localhost:35729/ 접속해서 {"tinylr":"Welcome","version":"1.0.3"} 출력되면 정상작동이다. tiny-lr의 기본 포트는 35729 이다.

const gulp = require('gulp');


function startExpress() {

  const express = require('express');

  const app = express();

  app.use(express.static(__dirname));

  app.listen(4000);

}


function startLivereload() {

  const lr = require('tiny-lr')();

  lr.listen(35729);

}


gulp.task('default', () => {

  startExpress();

  startLivereload();

});





Livereload 환경 만들기


전체 동작방식은 다음과 같다.

  - 브라우져가 열리면 livereload.js는 tiny-lr과 웹소켓 연결을 맺는다.

  - 1) gulp.watch가 파일 변경을 감지한다. 

  - 1) gulp.watch는 변경파일에 대해 tiny-lr에게 reload 하라고 호출한다. 

  - 2) tiny-lr 서버는 livereload.js 모듈과 웹소켓으로 통신한다.

  - 3) livereload.js는 파일을 다시 요청한다. 

  - 화면이 refresh되면서 livereload.js와 tiny-lr 간 웹소켓 연결을 다시 맺는다. 





Express로 서비스하는 페이지가 livereload 처리하는 자바스크립트 로직을 넣기위해 connect-livereload NodeJS 미들웨어도 설치한다.

$ yarn add --dev connect-livereload


connect-livereload를 Express 미들웨어로 설정한다.

// Gulpfile.ts

function startExpress() {

  const express = require('express');

  const app = express();

  app.use(require('connect-livereload')());

  app.use(express.static(__dirname));

  app.listen(4000);

}



gulp.watch를 통해 변경된 파일의 목록을 tiny-lr에 전달하는 코드를 작성한다. 

const gulp = require('gulp');


function startExpress() {

  const express = require('express');

  const app = express();

  app.use(require('connect-livereload')());

  app.use(express.static(__dirname));

  app.listen(4000);

}


let lr;

function startLivereload() {

  lr = require('tiny-lr')();

  lr.listen(35729);

}


function notifyLivereload(event) {

  // `gulp.watch()` events 는 절대경로를 주기 때문에 상대 경로(relative)를 만든다.

  var fileName = require('path').relative(__dirname, event.path);


  lr.changed({

    body: {

      files: [fileName]

    }

  });

}


gulp.task('default', () => {

  startExpress();

  startLivereload();

  gulp.watch('*.html', notifyLivereload);

});


다시 gulp를 수행하고 브라우져에서 http://localhost:4000/index.html 을 호출한 후에 index.html의 내용을 변경하면 브라우져가 자동으로 refresh되는 것을 볼 수 있다. 브라우져에서 element검사를 하면 아래와 같이 livereload.js파일이 </body> 전에 자동 추가된다. (소스 참조)



위의 코드를 단순히 하기위해 gulp-livereload를 사용할 수도 있다. 샘플 파일: https://github.com/BISTel-MIPlatform/livereload-tiny-lr





참조

  - https://github.com/mklabs/tiny-lr

 - https://github.com/livereload/livereload-js

  - https://github.com/intesso/connect-livereload

  - https://github.com/vohof/gulp-livereload

posted by 윤영식
2013. 9. 25. 09:16 My Services/Smart Visualization

SPA 방식의 개발을 위해서는 Client에 MV* Framework을 선택해야 한다. 초창기는 Backbone.js(이하, 백본)를 많이 사용하였고, 구현체로 Trello가 있으니 해당 서비스의 아키텍쳐를 참조해 보자. 그리고 SKT에서 코너스톤이라는 이름의 Framework도 백본을 사용하여 "웹앱"을 만들 수 있도록 안드로이드/iOS용 런타임 환경도 제공한다. 백본은 가벼우면서 광범위하게 많이 사용을 하고 있지만 개발 복잡성 비교에서 중간정도에 위치한다. 


<Trello 아키텍쳐>



브라우져에서 동작하는 애플리케이션의 템플릿이 .html 이면서 <chart ../> 와 같이 사용자 정의 html tag를 사용하여 View단을 좀 더 단순화 및 컴포넌트화 할 수 있는 AngularJS를 사용하기로 한다. AngularJS에는 여러 장점이 있지만 "웹 애플리케이션을 견고하게 만드는 방법" 블로깅을 통해 백본대신 왜 AngularJS를 선택했는지 갈음한다. AngularJs 프레임워크 기반의 SPA 개발을 위하여 쉽게 접근하는 방법은 도구를 통하여 하는 것인데, 오스마니님이 개발한 Yeoman을 통하여 AngularJS기반 프로젝트를 쉽게 구성할 수 있다. 



1. Yeoman 사용하기

  - 사전에 NodeJS 최신버전이 설치되어 있어야 한다. 

    설치후 npm (Node Package Manager)를 통하여 Yeoman(이하, yo)을 설치함

  - Yo 설치하기  : 가이드를 따라서 설치하면 된다 

    + yo : angular, express 등 관련 framework에 대한 scaffolding 프로젝트를 자동으로 만들어 주는 기능을 한다 

              generator-angular, generator-express와 같이 generator-*가 앞에 붙는다. npm 통하여 설치함 

              generator 만드는 방법은 "generator-angular와 express 연동하기" 블로그 참조한다 

    + bower : client단의 필요한 컴포넌트를 자동설치할 수 있다. 의존성관계 bower.json 파일에 설정한다. npm 과 유사함

    + grunt : 개발된 소스를 테스트, 빌드하는 javascript의 ant과 같은 역할을 한다. Gruntfile.js 에 설정한다 

    


  - yo 설치후 "yo -h" 수행하면 설치된 generator 목록을 볼 수 있다. 또는 yo라고 수행해도 된다 (보여지는 형식만 틀리다)

// generator와 관련된 MUST HAVE generator

$ sudo npm install -g generator-generator


// angularjs 관련 generator 설치 

$ sudo npm install -g generator-angular


// AngularJS 관련 scaffolding 명령 목록 

$ yo -h 

Angular

  angular:app  (default : angular) 

  angular:common

  angular:constant

  angular:controller

  angular:decorator

  angular:directive

  angular:factory

  angular:filter

  angular:main

  angular:provider

  angular:route

  angular:service

  angular:value

  angular:view


// express generator도 설치하자 

sudo npm install -g generator-express


* 여기서 잠깐!

만일 사용하는 OS가 Windows라면 지금 당장 Linux를 설치해서 사용한다. 우리가 배포하고 서비스하는 서버는 Cloud환경일 가능성이 다분히 높기 때문이다. Windows Server같은 곳에서 Node.js를 운영하는 것은 상상조차 하고 싶지 않다. 

  - Vagrant를 Windows에 설치해서 쉽게 Linux환경에 접근토록 하자



2. AngularJS 스케폴딩 만들기

  - yo를 통하여 AngularJS 기반의 SPA 프로젝트를 만든다. 여기에는 Node.js로 동작하는 서버 코드는 생성되지 않는다 

  - GitHub에 SmartVisualization 라고 생성을 한다. 각자의 계정에 만든다 

// GitHub의 저장소 clone 하고 angular 스케폴딩 명령 수행

$ git clone https://github.com/<자신의 아이디>/SmartVisualization.git  SmartVisualization

$ cd SmartVisualization

$ yo angular:app SmartVisualization

[?] Would you like to include Twitter Bootstrap? Yes

[?] Would you like to use the SCSS version of Twitter Bootstrap with the Compass CSS Authoring Framework? No

[?] Which modules would you like to include? (Press <space> to select)

❯⬢ angular-resource.js

 ⬢ angular-cookies.js

 ⬢ angular-sanitize.js


... 모듈들 자동 설치 중략 ...


// npm : package.json

// bower : .bowerrc, bower.json

// grunt : Gruntfile.js

// test 도구인 karma: karma*

// git 관련 : .git*

$ ls -alrt

-rw-r--r--   1 nulpulum  staff    11  2 21  2013 .gitattributes

-rw-r--r--   1 nulpulum  staff   415  4 16 00:02 .editorconfig

-rw-r--r--   1 nulpulum  staff   394  6 10 21:31 .jshintrc

-rw-r--r--   1 nulpulum  staff    56  6 10 21:31 .gitignore

-rw-r--r--   1 nulpulum  staff    44  6 10 21:31 .bowerrc

-rw-r--r--   1 nulpulum  staff   120  7 15 06:32 .travis.yml

-rw-r--r--   1 nulpulum  staff  1304  8 12 05:33 karma.conf.js

-rw-r--r--   1 nulpulum  staff  1348  8 12 05:33 karma-e2e.conf.js

drwxr-xr-x   5 nulpulum  staff   170  9 25 08:51 ..

drwxr-xr-x   5 nulpulum  staff   170  9 25 09:04 test

-rw-r--r--   1 nulpulum  staff   404  9 25 09:04 bower.json

-rw-r--r--   1 nulpulum  staff  8217  9 25 09:04 Gruntfile.js

drwxr-xr-x  12 nulpulum  staff   408  9 25 09:04 app

drwxr-xr-x  16 nulpulum  staff   544  9 25 09:04 .

drwxr-xr-x  39 nulpulum  staff  1326  9 25 09:04 node_modules

-rw-r--r--   1 nulpulum  staff  1466  9 25 09:05 package.json


  - Yeoman을 통하여 AngularJS 프로젝트 스케폴딩을 만들었다면 Grunt명령을 통하여 테스팅을 위한 서버를 기동할 수 있다 

// 명령을 수행하면 Node.js를 기반으로 서버가 기동하고 9000 port로 Chrome브라우져가 자동 실행되어 호출된다

// Grunt는 Java의 Ant와 같은 도구이다 

$ grunt server

Running "server" task


Running "clean:server" (clean) task

Cleaning .tmp...OK


Running "concurrent:server" (concurrent) task


    Running "copy:styles" (copy) task

    Copied 2 files

    

    Done, without errors.


    Elapsed time

    copy:styles  15ms

    Total        16ms


    Running "coffee:dist" (coffee) task


    Done, without errors.


    Elapsed time

    coffee:dist  10ms

    Total        10ms


Running "autoprefixer:dist" (autoprefixer) task

File ".tmp/styles/bootstrap.css" created.

File ".tmp/styles/main.css" created.


Running "connect:livereload" (connect) task

Started connect web server on localhost:9000.


Running "open:server" (open) task


Running "watch" task

Waiting...


// 브라우져 자동 실행 및 9000 포트 자동 호출된 결과물 


다음은 AngularJS 에 대하여 알아보자



<참조>

  - Client MV* Framework에대한 ToDoMVC 개발 복잡성 비교

  - Yeoman의 generator-angular와 express 연동하기

  - Vagrant를 통하여 개발환경 꾸미기

posted by 윤영식
2013. 1. 29. 21:57 NodeJS/Prototyping

Node.js를 설치하고 MongoDB를 사용하여 REST API를 만들어보자. native MongoDB driver를 사용하며 REST API를 쉽게 만들기 위하여 Node.js의 웹애플리케이션 프레임워크인 Express를 이용한다. 원문의 내용을 보고 수행한 결과를 요약한다 



1) Node.js 설치 

  - http://nodejs.org/dist/  : 사이트에서 최신 버전을 선택하여 다운로드한다 

  - 예) linux 

[mongodb@localhost ~]$ wget http://nodejs.org/dist/v0.9.8/node-v0.9.8-linux-x86.tar.gz 

--2013-02-01 21:24:48--  http://nodejs.org/dist/v0.9.8/node-v0.9.8-linux-x86.tar.gz

Resolving nodejs.org... 165.225.133.150

Connecting to nodejs.org|165.225.133.150|:80... connected.

HTTP request sent, awaiting response... 200 OK

Length: 4491882 (4.3M) [application/octet-stream]

Saving to: “node-v0.9.8-linux-x86.tar.gz”


100%[=========================================================>] 4,491,882    284K/s   in 17s     


2013-02-01 21:25:07 (263 KB/s) - “node-v0.9.8-linux-x86.tar.gz” saved [4491882/4491882]


[mongodb@localhost ~]$ ls

aggregation  mongo  mongod  mongodb  mongofiles  mongos  node-v0.9.8-linux-x86.tar.gz  shard

[mongodb@localhost ~]$ tar zxf node-v0.9.8-linux-x86.tar.gz

[mongodb@localhost ~]$ ls

aggregation  mongod   mongofiles  node-v0.9.8-linux-x86         shard

mongo        mongodb  mongos      node-v0.9.8-linux-x86.tar.gz

[mongodb@localhost ~]$ rm node-v0.9.8-linux-x86.tar.gz

[mongodb@localhost ~]$ mv node-v0.9.8-linux-x86 node-v0.9.8

[mongodb@localhost ~]$ ls

aggregation  mongo  mongod  mongodb  mongofiles  mongos  node-v0.9.8  shard

[mongodb@localhost ~]$ cd node-v0.9.8/

[mongodb@localhost node-v0.9.8]$ cd bin

[mongodb@localhost bin]$ ./node -v

v0.9.8


2) Node.js 수행하기 

  - 적당한 디렉토리에 nodecellar 디렉토리 만듦

  - nodecellar 안에 server.js 파일 생성

  - server.js 코딩 

////////////////////////////////////////////////
// server.js
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3000/');


  - server.js 수행하고 브라우져에서 http://127.0.0.1:3000/ 호출 

[mongodb@localhost ~]$ cd nodecellar/

[mongodb@localhost nodecellar]$ node server.js

Server running at http://127.0.0.1:3000/



3) Express 설치하기 

  - Node.js의 Web Application Framework 이고, REST API 생성을 쉽게 해준다 

  - nodecellar 디렉토리안에 package.json 파일을 만들어서 Node.js가 의존하는 모듈을 정의한다 

////////////////////////////////////////////
// package.json
{
    "name": "wine-cellar",
    "description": "Wine Cellar Application",
    "version": "0.0.1",
    "private": true,
    "dependencies": {
        "express": "3.x"
    }
}

  - express 설치하기 

// package.json의 의존관계 모듈을 읽어서 자동 설치해 준다 

[mongodb@localhost nodecellar]$ npm install

npm WARN package.json wine-cellar@0.0.1 No README.md file found!

npm http GET https://registry.npmjs.org/express

npm http 200 https://registry.npmjs.org/express

npm http GET https://registry.npmjs.org/express/-/express-3.1.0.tgz

... 중략 ...
express@3.1.0 node_modules/express
├── methods@0.0.1
├── fresh@0.1.0
├── range-parser@0.0.4
├── cookie-signature@0.0.1
├── buffer-crc32@0.1.1
├── cookie@0.0.5
├── commander@0.6.1
├── debug@0.7.0
├── mkdirp@0.3.3
├── send@0.1.0 (mime@1.2.6)
└── connect@2.7.2 (pause@0.0.1, bytes@0.1.0, formidable@1.0.11, qs@0.5.1)



4) server.js를 Express 형식으로 바꾸기 

  - express 프레임워크를 이용하여 HTTP Listener를 바꾼다

////////////////////////////////////////////
// server.js
var express = require('express');
 var app = express();
 
app.get('/wines', function(req, res) {
    res.send([{name:'wine1'}, {name:'wine2'}]);
});
app.get('/wines/:id', function(req, res) {
    res.send({id:req.params.id, name: "The Name", description: "description"});
});
 
app.listen(3000);
console.log('Express Listening on port 3000...');

  - express 실행

[mongodb@localhost nodecellar]$ node server

Express Listening on port 3000...


  - 브라우져 호출하기 

    + 전체 wine들 

  

    + 1번 wine 내역 

  


5) Node.js에서 Controller로써 routes를 만들기 

  - nodecellar 디렉토리 밑으로 routes 폴더를 만든다 

  - routes 밑에 모듈로 wines.js 를 만든다 

////////////////////////////////////////////
// routes 디렉토리 밑의 wines.js
exports.findAll = function(req, res) {
    res.send([{name:'wine1'}, {name:'wine2'}, {name:'wine3'}]);
};
 
exports.findById = function(req, res) {
    res.send({id:req.params.id, name: "The Name", description: "description"});
};


  - server.js 파일에서 wines.js 모듈을 로딩하게 한다. 그리고 다시 브라우져로 호출한다 

////////////////////////////////////////////
// server.js에서 wines.js 모듈 로딩
var express = require('express'),
    wines = require('./routes/wines');
var app = express();
 
app.get('/wines', wines.findAll);
app.get('/wines/:id', wines.findById);
 
app.listen(3000);
console.log('Express Listening on port 3000...');


6) MongoDB Driver 설치하기 

  - MongoDB는 설치되어 있다고 가정한다 (참조)

  - 여기서는 native Node.js driver를 사용한다

  - mongodb driver 설치하기 

[mongodb@localhost nodecellar]$ npm install mongodb

npm WARN package.json wine-cellar@0.0.1 No README.md file found!

npm http GET https://registry.npmjs.org/mongodb

...  중략 ...

npm http GET https://registry.npmjs.org/bson/-/bson-0.1.6.tgz

... 중략 ...

node-gyp clean

node-gyp configure build

gyp http GET http://nodejs.org/dist/v0.9.8/node-v0.9.8.tar.gz

gyp http 200 http://nodejs.org/dist/v0.9.8/node-v0.9.8.tar.gz

make[1]: Entering directory `/home/mongodb/nodecellar/node_modules/mongodb/node_modules/bson/build'

  CXX(target) Release/obj.target/bson/ext/bson.o

  SOLINK_MODULE(target) Release/obj.target/bson.node

  SOLINK_MODULE(target) Release/obj.target/bson.node: Finished

  COPY Release/bson.node

make[1]: Leaving directory `/home/mongodb/nodecellar/node_modules/mongodb/node_modules/bson/build'

child process exited with code 0

mongodb@1.2.11 node_modules/mongodb

└── bson@0.1.6



7) REST API 정의하기 

  - 호출 내역 

    + GET: 전체 wine 목록

    + GET: id로 선택된 wine 정보얻기 

    + POST: 새로운 wine 생성

    + PUT: id로 선택된 wine 정보갱신

    + DELETE: id로 선택된 wine 삭제하기 

  

  

  - server.js에서 wines.js를 확장한 메소드를 추가한다 

  - wines.js 안에 MongoDB 코드로 변경하기 



8) MongoDB 와 Node.js 수행하고 Testing 하기 

  - MongoDB는 default port로 수행한다 

[mongodb@localhost ~]$ ./mongod --dbpath /home/mongodb/aggregation

... 중략 ...

Fri Feb  1 22:30:46 [initandlisten] options: { dbpath: "/home/mongodb/aggregation" }

Fri Feb  1 22:30:46 [initandlisten] Unable to check for journal files due to: boost::filesystem::basic_directory_iterator constructor: No such file or directory: "/home/mongodb/aggregation/journal"

Fri Feb  1 22:30:46 [initandlisten] couldn't unlink socket file /tmp/mongodb-27017.sockerrno:1 Operation not permitted skipping

Fri Feb  1 22:30:46 [initandlisten] waiting for connections on port 27017

Fri Feb  1 22:30:46 [websvr] admin web console waiting for connections on port 28017



  - Node.js 수행하기 

     + MongoDB의 기본 port 27017 로 접근한다 

[mongodb@localhost nodecellar]$ node server

========================================================================================

=  Please ensure that you set the default write concern for the database by setting    =

=   one of the options                                                                 =

=                                                                                      =

=     w: (value of > -1 or the string 'majority'), where < 1 means                     =

=        no write acknowlegement                                                       =

=     journal: true/false, wait for flush to journal before acknowlegement             =

=     fsync: true/false, wait for flush to file system before acknowlegement           =

=                                                                                      =

=  For backward compatibility safe is still supported and                              =

=   allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}]      =

=   the default value is false which means the driver receives does not                =

=   return the information of the success/error of the insert/update/remove            =

=                                                                                      =

=   ex: new Db(new Server('localhost', 27017), {safe:false})                           =

=                                                                                      =

=   http://www.mongodb.org/display/DOCS/getLastError+Command                           =

=                                                                                      =

=  The default of no acknowlegement will change in the very near future                =

=                                                                                      =

=  This message will disappear when the default safe is set on the driver Db           =

========================================================================================

Express Listening on port 3000...

Connected to 'winedb' database


  - curl을 수행한다 

/////////////////////////////////////////

// POST를 통하여 신규 wine을 생성한다

[mongodb@localhost ~]$ curl -i -X POST -H 'Content-Type: application/json' -d '{"name": "New Wine", "year": "2009"}' http://localhost:3000/wines

HTTP/1.1 200 OK

X-Powered-By: Express

Content-Type: application/json; charset=utf-8

Content-Length: 79

Date: Sat, 02 Feb 2013 06:38:49 GMT

Connection: keep-alive


{

  "name": "New Wine",

  "year": "2009",

  "_id": "510cb4798859a9b51d000001"


/////////////////////////////////////////

// MongoDb 확인 

[mongodb@localhost ~]$ mongo

MongoDB shell version: 2.2.2

connecting to: test

> show dbs

dowonDB 0.03125GB

local (empty)

winedb 0.0625GB

> use winedb

switched to db winedb

> show collections

system.indexes

wines

> db.wines.find()

{ "name" : "New Wine", "year" : "2009", "_id" : ObjectId("510cb4798859a9b51d000001") }


/////////////////////////////////////////

// GET 명령 수행하여 정보 조회

// wine 목록을 얻어온다.

[mongodb@localhost ~]$ curl -i -X GET http://localhost:3000/wines

HTTP/1.1 200 OK

X-Powered-By: Express

Content-Type: application/json; charset=utf-8

Content-Length: 93

Date: Sat, 02 Feb 2013 06:41:37 GMT

Connection: keep-alive


[

  {

    "name": "New Wine",

    "year": "2009",

    "_id": "510cb4798859a9b51d000001"

  }

]


// 특정 wine 조회. _id를 넣어준다 

[mongodb@localhost ~]$ curl -i -X GET http://localhost:3000/wines/510cb4798859a9b51d000001

HTTP/1.1 200 OK

X-Powered-By: Express

Content-Type: application/json; charset=utf-8

Content-Length: 79

Date: Sat, 02 Feb 2013 06:42:14 GMT

Connection: keep-alive


{

  "name": "New Wine",

  "year": "2009",

  "_id": "510cb4798859a9b51d000001"



/////////////////////////////////////////

// PUT 명령 수행하여 정보 수정 

[mongodb@localhost ~]$ curl -i -X PUT -H 'Content-Type: application/json' -d '{"name": "New Wine", "year": "2010"}' http://localhost:3000/wines/510cb4798859a9b51d000001
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 42
Date: Sat, 02 Feb 2013 06:44:00 GMT
Connection: keep-alive

{
  "name": "New Wine",
  "year": "2010"


/////////////////////////////////////////

// DELETE 명령 수행하여 정보 삭제

[mongodb@localhost ~]$ curl -i -X DELETE http://localhost:3000/wines/510cb4798859a9b51d000001
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 2
Date: Sat, 02 Feb 2013 06:46:22 GMT
Connection: keep-alive

/////////////////////////////////////////

// MongoDb 확인 

[mongodb@localhost ~]$ mongo
MongoDB shell version: 2.2.2
connecting to: test
> use winedb
switched to db winedb
> show collections
system.indexes
wines
> db.wines.find()    <=== 데이터가 삭제되어 없음 



<참조>

  - 원문 : Creating a REST API using Node.js, Express, and MongoDB

  - 참조 

    + https://speakerdeck.com/jakobmattsson/writing-restful-web-services-using-nodejs

    + Node.js 설치하기

    + MongoDB 설치하기

  - 심화 : Backbone.js 와 Bootstrap, Node.js로 만들기 

posted by 윤영식
prev 1 next