This module is the lightest possible wrapper on top of node.js http, but supporting these essential features:
follows redirects
automatically handles gzip/deflate responses
supports HTTPS
supports specifying a timeout
supports convenience url key so there's no need to use url.parse on the url when specifying options
composes well with npm packages for features like cookies, proxies, form data, & OAuth
All this in < 120 lines of code.
install
npm install simple-get
usage
Note, all these examples also work in the browser with browserify.
simple GET request
Doesn't get easier than this:
const get = require('simple-get')get('http://example.com', function (err, res) { if (err) throw err console.log(res.statusCode) // 200 res.pipe(process.stdout) // `res` is a stream})
even simpler GET request
If you just want the data, and don't want to deal with streams:
const get = require('simple-get')get.concat('http://example.com', function (err, res, data) { if (err) throw err console.log(res.statusCode) // 200 console.log(data) // Buffer('this is the server response')})
POST, PUT, PATCH, HEAD, DELETE support
For POST, call get.post or use option { method: 'POST' }.
const get = require('simple-get')const opts = { url: 'http://example.com', body: 'this is the POST body'}get.post(opts, function (err, res) { if (err) throw err res.pipe(process.stdout) // `res` is a stream})
A more complex example:
const get = require('simple-get')get({ url: 'http://example.com', method: 'POST', body: 'this is the POST body', // simple-get accepts all options that node.js `http` accepts // See: http://nodejs.org/api/http.html#http_http_request_options_callback headers: { 'user-agent': 'my cool app' }}, function (err, res) { if (err) throw err // All properties/methods from http.IncomingResponse are available, // even if a gunzip/inflate transform stream was returned. // See: http://nodejs.org/api/http.html#http_http_incomingmessage res.setTimeout(10000) console.log(res.headers) res.on('data', function (chunk) { // `chunk` is the decoded response, after it's been gunzipped or inflated // (if applicable) console.log('got a chunk of the response: ' + chunk) }))})
JSON
You can serialize/deserialize request and response with JSON:
const get = require('simple-get')const opts = { method: 'POST', url: 'http://example.com', body: { key: 'value' }, json: true}get.concat(opts, function (err, res, data) { if (err) throw err console.log(data.key) // `data` is an object})
Timeout
You can set a timeout (in milliseconds) on the request with the timeout option.
If the request takes longer than timeout to complete, then the entire request
will fail with an Error.
const get = require('simple-get')const opts = { url: 'http://example.com', timeout: 2000 // 2 second timeout}get(opts, function (err, res) {})
One Quick Tip
It's a good idea to set the 'user-agent' header so the provider can more easily
see how their resource is used.