Skip to content

Commit

Permalink
return Promise when callback missing. fixed #33
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Aug 25, 2014
1 parent 02c784d commit 79debd8
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 6 deletions.
45 changes: 42 additions & 3 deletions README.md
Expand Up @@ -28,9 +28,6 @@
Help in opening URLs (mostly HTTP) in a complex world — basic
and digest authentication, redirections, cookies, timeout and more.

If you are using [co](https://github.com/visionmedia/co) or [koa](https://github.com/koajs/koa),
please take a look at [co-urllib](https://github.com/node-modules/co-urllib).

## Install

```bash
Expand All @@ -39,6 +36,8 @@ $ npm install urllib --save

## Usage

### callback

```js
var urllib = require('urllib');

Expand All @@ -53,6 +52,44 @@ urllib.request('http://cnodejs.org/', { wd: 'nodejs' }, function (err, data, res
});
```

### Promise

If you've installed [bluebird][bluebird],
[bluebird][bluebird] will be used.
`urllib` does not install [bluebird][bluebird] for you.

Otherwise, if you're using a node that has native v8 Promises (v0.11.13+),
then that will be used.

Otherwise, this library will crash the process and exit,
so you might as well install [bluebird][bluebird] as a dependency!

```js
var urllib = require('urllib');

urllib.request('http://nodejs.org').then(function (result) {
// result: {data: buffer, res: response object}
console.log('status: %s, body size: %d, headers: %j', result.res.statusCode, result.data.length, result.res.headers);
}).error(function (err) {
console.error(err);
});
```

### co & generator

If you are using [co](https://github.com/visionmedia/co) or [koa](https://github.com/koajs/koa):

```js
var co = require('co');
var urllib = require('urllib');

co(function* () {
var result = yield urllib.request('http://nodejs.org');
console.log('status: %s, body size: %d, headers: %j',
result.res.statusCode, result.data.length, result.res.headers);
})();
```

## API Doc

### Method: `http.request(url[, options][, callback])`
Expand Down Expand Up @@ -281,3 +318,5 @@ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

[bluebird]: https://github.com/petkaantonov/bluebird
8 changes: 8 additions & 0 deletions examples/co_urllib.js
@@ -0,0 +1,8 @@
var co = require('co');
var urllib = require('../');

co(function* () {
var result = yield urllib.request('http://nodejs.org');
console.log('status: %s, body size: %d, headers: %j',
result.res.statusCode, result.data.length, result.res.headers);
})();
7 changes: 7 additions & 0 deletions examples/promise_urllib.js
@@ -0,0 +1,7 @@
var urllib = require('../');

urllib.request('http://nodejs.org').then(function (result) {
console.log('status: %s, body size: %d, headers: %j', result.res.statusCode, result.data.length, result.res.headers);
}).error(function (err) {
console.error(err);
});
34 changes: 33 additions & 1 deletion lib/urllib.js
Expand Up @@ -25,6 +25,7 @@ var fs = require('fs');
var zlib = require('zlib');
var ua = require('default-user-agent');
var digestAuthHeader = require('digest-header');
var _Promise;

var pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '../', 'package.json')));

Expand Down Expand Up @@ -100,6 +101,36 @@ exports.request = function (url, args, callback) {
callback = args;
args = null;
}
if (typeof callback === 'function') {
return exports.requestWithCallback(url, args, callback);
}

// Promise
if (!_Promise) {
_Promise = require('native-or-bluebird');
}
return new _Promise(function (resolve, reject) {
exports.requestWithCallback(url, args, makeCallback(resolve, reject));
});
};

function makeCallback(resolve, reject) {
return function (err, data, res) {
if (err) {
return reject(err);
}
resolve({
data: data,
res: res
});
};
}

exports.requestWithCallback = function (url, args, callback) {
if (typeof args === 'function') {
callback = args;
args = null;
}

args = args || {};

Expand Down Expand Up @@ -316,7 +347,8 @@ exports.request = function (url, args, callback) {
var writeStream = args.writeStream;

var reqId = ++REQUEST_ID;
debug('Request#%d %s %s with headers %j', reqId, method, url, options.headers);
debug('Request#%d %s %s with headers %j, options.path',
reqId, method, url, options.headers, options.path);
var req = httplib.request(options, function (res) {
connnected = true;
debug('Request#%d %s `req response` event emit: status %d, headers: %j',
Expand Down
6 changes: 4 additions & 2 deletions package.json
Expand Up @@ -32,9 +32,10 @@
"debug": "~1.0.4",
"default-user-agent": "~0.0.1",
"digest-header": "~0.0.1",
"should-http": "0.0.2"
"native-or-bluebird": "~1.0.0"
},
"devDependencies": {
"bluebird": "*",
"agentkeepalive": "~0.2.0",
"autod": "*",
"contributors": "*",
Expand All @@ -43,7 +44,8 @@
"jshint": "*",
"mocha": "*",
"pedding": "~1.0.0",
"should": "~4.0.4"
"should": "~4.0.4",
"should-http": "0.0.2"
},
"engines": {
"node": ">= 0.10.0"
Expand Down
48 changes: 48 additions & 0 deletions test/urllib_promise.test.js
@@ -0,0 +1,48 @@
/**!
* urllib - test/urllib_promise.test.js
*
* Copyright(c) fengmk2 and other contributors.
* MIT Licensed
*
* Authors:
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
*/

'use strict';

/**
* Module dependencies.
*/

var should = require('should');
var urllib = require('../');

describe('urllib_promise.test.js', function () {
it('should return promise when callback missing', function (done) {
urllib.request('http://nodejs.org')
.then(function (result) {
should.exist(result.data);
should.exist(result.res);
result.data.should.be.a.Buffer;
result.res.should.status(200);
result.res.should.have.header('connection', 'keep-alive');
done();
}).error(done);
});

it('should work with args', function (done) {
urllib.request('http://nodejs.org', {
data: {
q: 'foo'
}
})
.then(function (result) {
should.exist(result.data);
should.exist(result.res);
result.data.should.be.a.Buffer;
result.res.should.status(200);
result.res.should.have.header('connection', 'keep-alive');
done();
}).error(done);
});
});

0 comments on commit 79debd8

Please sign in to comment.