오늘은 node.js modules you should know about 연재의 네 번째 시간이다.

1회 연재 - dnode (RPC 라이브러리)

2회 연재 - optimist (옵션 파서)

3회 연재 - lazy (lazy 리스트 처리)

이번에 내가 소개할 모듈은 Mikeal Rogers가 개발한 아주 훌륭한 request라는 놈이다.  request는 HTTP 스트림 처리를 위한 만능 모듈이다.

다음 예제를 살펴보자.

var fs = require('fs')
var request = require('request');

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

여러분은 방금 http://google.com/doodle.png 으로 HTTP 요청에 대한 응답을 받아 doodle.png로컬 파일을 생성했다.

다음은 더 놀라운 예제다.

var fs = require('fs')
var request = require('request');

fs.readStream('file.json').pipe(request.put('http://mysite.com/obj.json'))

와우! 위 코드는 여러분의 로컬 파일 file.jsonhttp://mysite.com/obj.json으로 HTTP PUT 요청을 통해 보내는 것이다.

var request = require('request');

request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))

와우! 위 예제 코드는 http://google.com/img.png의 내용을 HTTP GET으로 읽어서 http://mysite.com/img.png 위치에 HTTP PUT를 통해 보내는 것이다.

Browserling (역자주: 저자가 세운 스타트업 회사)에서는 couchdb로 데이터를 보내거나 받을 때, 이 모듈을 사용한다. 다음은 mikea의 테스트 couchdb에 JSON 문서를 저장하는 예제이다.

var request = require('request')
var rand = Math.floor(Math.random()*100000000).toString()

request({
  method: 'PUT',
  uri: 'http://mikeal.iriscouch.com/testjs/' + rand,
  multipart: [
    {
      'content-type': 'application/json',
      'body': JSON.stringify({
        foo: 'bar',
        _attachments: {
          'message.txt': {
            follows: true,
            length: 18,
            'content_type': 'text/plain'
           }
         }
       })
    },
    { body: 'I am an attachment' }
  ]
}, function (error, response, body) {
  if(response.statusCode == 201){
    console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand);
  } else {
    console.log('error: '+ response.statusCode);
    console.log(body);
  }
})

늘 그랬던 것처럼, 다음과 같이 npm을 통해 request 모듈을 설치해라.

npm install request

[역자주 - 이 모듈은 HTTP 처리를 하는데 굉장히 유용한 모듈이다. 비슷한 작업을 하고 있다면, node.js의 http 코어 모듈을 사용하는 것 대신에 사용해 볼것을 고려해 볼 만하다.]

If you love these articles, subscribe to my blog for more, follow me on Twitter to find about my adventures, and watch me produce code on GitHub!