diff --git a/.jshintrc b/.jshintrc index c07344f..eae03a4 100644 --- a/.jshintrc +++ b/.jshintrc @@ -63,6 +63,7 @@ "node":true, "globals": { + "Promise":true }, "predef": [ diff --git a/README.md b/README.md index b062e27..ad15418 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,39 @@ ## Usage +Function to hit a URL and stop as soon as headers are received i.e. do not fetch the body of the HTTP response. + +Useful for example for checking the size of a large file without downloading it. Uses GET HTTP method (or whatever method requested) rather than HEAD as some servers may not support HEAD, or not use cookies with HEAD etc. + +Returns a [Bluebird](https://www.npmjs.com/package/bluebird) Promise which resolves to the response object, or rejects with an error. + +Uses [got](https://www.npmjs.com/package/got) to make the HTTP request. + +### headers(url, [options]) + +```js +const headers = require('got-headers'); + +headers('http://www.google.com').then(function(res) { + // Print headers object + console.log(res.headers); +}).catch(function(err) { + // Print error + console.log('Error!', err); + + // Print response object + console.log(err.res); +}); +``` + +`options` object is passed directly to [got](https://www.npmjs.com/package/got) - use any of got's options. + ## Tests Use `npm test` to run the tests. Use `npm run cover` to check coverage. +There are no tests at present but it seems to work fine! + ## Changelog See [changelog.md](https://github.com/overlookmotel/got-headers/blob/master/changelog.md) diff --git a/changelog.md b/changelog.md index 57855bc..94a1afe 100644 --- a/changelog.md +++ b/changelog.md @@ -1,3 +1,5 @@ # Changelog ## Next + +* Initial release diff --git a/lib/index.js b/lib/index.js index c9054a8..22aac29 100644 --- a/lib/index.js +++ b/lib/index.js @@ -4,6 +4,34 @@ 'use strict'; +// Modules +const got = require('got'), + Promise = require('bluebird'); + // Exports -module.exports = function() { + +/** + * Hit URL and get headers only + * @param {string} url - URL + * @param {Object} [options] - Options object to pass to `got` + * @returns {Promise} - Bluebird Promise which resolves with response object + */ +module.exports = function(url, options) { + return new Promise((resolve, reject) => { + const stream = got.stream(url, options); + + let req; + stream.on('request', _req => req = _req); + + stream.on('response', res => { + req.abort(); + resolve(res); + }); + + stream.on('error', (err, body, response) => { + err.body = body; + err.response = response; + reject(err); + }); + }); }; diff --git a/package.json b/package.json index 9908989..a2e5269 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,8 @@ "url": "https://github.com/overlookmotel/got-headers/issues" }, "dependencies": { + "got": "^7.0.0", + "bluebird": "^3.5.0" }, "devDependencies": { "chai": "^4.0.2",