Compare commits

...

33 Commits

Author SHA1 Message Date
AJ ONeal bb30d5acf6
1.8.2 2022-06-14 01:37:28 -06:00
AJ ONeal 5b539deb7b
fix: copy http options from opts (not opts.uri) 2022-06-14 01:24:50 -06:00
AJ ONeal 0a2e7afa76
1.8.1 2022-01-12 12:45:07 -07:00
AJ ONeal ba60df7eab
fix: don't JSON.stringify a string body, duh 2022-01-12 12:42:34 -07:00
AJ ONeal bc4f6e59c0 1.8.0 2021-10-18 01:42:07 -06:00
AJ ONeal 3842ee1d61 docs: add CHANGELOG.md 2021-10-18 01:41:08 -06:00
AJ ONeal 9518cb970b feature: add resp.stream.body() and resp.ok 2021-10-18 01:38:44 -06:00
AJ ONeal 2e9a643c0f feature: fail faster on bad createWriteStream 2021-10-18 00:55:04 -06:00
AJ ONeal dcd41a33d0 chore: add linter config 2021-10-18 00:47:39 -06:00
AJ ONeal 5f5e0b6066 bugfix: return after error callback 2021-10-18 00:47:06 -06:00
AJ ONeal ed2bab931f
Update README.md 2021-08-20 22:57:43 -06:00
AJ ONeal a95d003ed5
docs: link to form-data v2.x (JavaScript) docs 2021-08-06 15:27:06 -06:00
AJ ONeal 5149bc9dcb
docs: clarify stream usage 2021-08-06 14:07:03 -06:00
AJ ONeal 95a12a8285 v1.7.0 add stream support 2021-01-14 16:35:07 -07:00
AJ ONeal 9395ec96e3 make Prettier (v2) 2021-01-14 16:07:48 -07:00
AJ ONeal 3574e35635 v1.6.1: userAgent and docs 2020-04-28 23:14:50 -06:00
AJ ONeal 508f1ce591 add comments 2020-04-28 23:00:26 -06:00
AJ ONeal c2c4b5b2de v1.6.0: add default User-Agent, bugfixes 2020-04-28 22:58:11 -06:00
AJ ONeal f6557b7610 handle possible readable body error 2020-04-28 22:56:12 -06:00
AJ ONeal 4b9a1f07ee add default User-Agent 2020-04-28 22:43:27 -06:00
AJ ONeal e22baa8eae v1.5.0: add pipe support, fix bearer bug 2020-03-12 02:01:23 -06:00
AJ ONeal 812f4e6062 bugfix request compat opts.auth.bearer 2020-03-12 01:59:33 -06:00
AJ ONeal 5b5cd36aa5 allow pipe-able inputs 2020-03-12 01:57:10 -06:00
AJ ONeal 4f3fe38ee4 update docs for promises 2020-02-27 02:17:07 +00:00
AJ ONeal ef3183e984 add 80/20 message 2020-02-20 17:34:27 +00:00
AJ ONeal e384aead9b v1.4.2: regression fix: copy 'method' to final object 2019-11-01 01:19:47 -06:00
AJ ONeal 87bf5a5fc5 v1.4.2: regression fix: copy 'method' to final object 2019-11-01 01:18:25 -06:00
AJ ONeal 1692b9e7df v1.4.1: GET by default *after* POST body check 2019-10-29 21:53:39 -06:00
AJ ONeal 8f5133385b v1.4.0: add promise support and easy debugging 2019-10-29 14:57:28 -06:00
AJ ONeal 1507b38503 v1.3.12: bugfix json request 2019-10-29 14:42:26 -06:00
AJ ONeal 9ab91d9721 make Prettier 2019-10-29 14:31:30 -06:00
AJ ONeal b6900b937b remove extraneous variable 2019-06-04 04:20:29 +00:00
AJ ONeal be91c1b78f show promise usage 2019-06-04 04:19:11 +00:00
19 changed files with 1125 additions and 562 deletions

22
.jshintrc Normal file
View File

@ -0,0 +1,22 @@
{
"browser": true,
"node": true,
"esversion": 11,
"curly": true,
"sub": true,
"bitwise": true,
"eqeqeq": true,
"forin": true,
"freeze": true,
"immed": true,
"latedef": "nofunc",
"nonbsp": true,
"nonew": true,
"plusplus": true,
"undef": true,
"unused": "vars",
"strict": true,
"maxdepth": 3,
"maxstatements": 100,
"maxcomplexity": 40
}

8
.prettierrc Normal file
View File

@ -0,0 +1,8 @@
{
"bracketSpacing": true,
"printWidth": 80,
"singleQuote": true,
"tabWidth": 4,
"trailingComma": "none",
"useTabs": false
}

6
CHANGELOG.md Normal file
View File

@ -0,0 +1,6 @@
# CHANGELOG
## v1.8.0
- add `resp.ok` - same as WHATWG fetch `resp.ok = (resp.statusCode >= 200 && resp.statusCode < 300)`
- add `resp.stream.body()` to populate `resp.body` rather than (or perhaps in addition to) continuing to stream (useful for error handling)

65
EXTRA.md Normal file
View File

@ -0,0 +1,65 @@
# Extra
There are some niche features of @root/request which are beyond the request.js
compatibility.
## async/await & Promises
The differences in async support are explained in [README.md](/README.md), up near the top.
If you're familiar with Promises (and async/await), then it's pretty self-explanatory.
## ok
Just like WHATWG `fetch`, we have `resp.ok`:
```js
let resp = await request({
url: 'https://example.com'
}).then(mustOk);
```
```js
function mustOk(resp) {
if (!resp.ok) {
// handle error
throw new Error('BAD RESPONSE');
}
return resp;
}
```
## streams
The differences in stream support are explained in [README.md](/README.md), up near the top.
## userAgent
There's a default User-Agent string describing the version of @root/request, node.js, and the OS.
Add to the default User-Agent
```js
request({
// ...
userAgent: 'my-package/1.0' // add to agent
});
```
Replace the default User-Agent
```js
request({
// ...
headers: { 'User-Agent': 'replace/0.0' }
});
```
Disable the default User-Agent:
```js
request({
// ...
headers: { 'User-Agent': false }
});
```

191
README.md
View File

@ -1,17 +1,21 @@
# [µRequest](https://git.rootprojects.org/root/request.js) | a [Root](https://rootprojects.org) project # [@root/request](https://git.rootprojects.org/root/request.js) | a [Root](https://rootprojects.org) project
> Minimalist HTTP client > Minimalist HTTP client
A lightweight alternative to (and drop-in replacement for) request. A lightweight alternative to (and 80/20 drop-in replacement for) request.
Has the 20% of features that 80%+ of people need, in about 500 LoC.
Written from scratch, with zero-dependencies. Written from scratch, with zero-dependencies.
## Super simple to use ## Super simple to use
µRequest is designed to be a drop-in replacement for request. It supports HTTPS and follows redirects by default. @root/request is designed to be a drop-in replacement for request. It also supports Promises and async/await by default, enhanced stream support, and a few other things as mentioned below.
```bash ```bash
npm install --save @root/request npm install --save @root/request
# or npm install git+ssh://git@git.therootcompany.com/request.js
``` ```
```js ```js
@ -23,17 +27,121 @@ request('http://www.google.com', function (error, response, body) {
}); });
``` ```
**Using Promises**
```js
var request = require('@root/request');
request('http://www.google.com')
.then(function (response) {
console.log('statusCode:', response.statusCode); // Print the response status code if a response was received
console.log('body:', response.body); // Print the HTML for the Google homepage.
})
.catch(function (error) {
console.log('error:', error); // Print the error if one occurred
});
```
**Streaming**
In order to keep this library lightweight, performant, and keep the code easy to
read, the streaming behavior is **_slightly different_** from that of
`request.js`.
```diff
-var request = require('request');
+var request = require('@root/request');
-var stream = request({ url, headers });
+var stream = await request({ url, headers });
let attachment = await new MailgunAPI.Attachment({
data: stream
})
```
Example:
```js
var request = require('@root/request');
var resp = await request({
url: 'http://www.google.com',
stream: true // true | 'filename.ext' | stream.Writable
});
// 'resp' itself is a ReadableStream
resp.on('data', function () {
// got some data
});
resp.on('end', function () {
// the data has ended
});
// 'resp.stream' is a Promise that is resolved when the read stream is destroyed
await resp.stream; // returns `undefined`
console.log('Done');
```
The difference is that we don't add an extra layer of stream abstraction.
You must use the response from await, a Promise, or the callback.
You can also give a file path:
```js
request({
url: 'http://www.google.com',
stream: '/tmp/google-index.html'
});
```
Which is equivalent to passing a write stream for the file:
```js
request({
url: 'http://www.google.com',
stream: fs.createWriteStream('/tmp/google-index.html')
});
```
Also, `await resp.stream.body()` can be used to get back the full body (the same as if you didn't use the `stream` option:
```js
let resp = await request({
url: 'http://www.google.com',
stream: true
});
if (!resp.ok) {
await resp.stream.body();
console.error(resp.body);
}
```
## Table of contents ## Table of contents
- [Extra Features](/EXTRA.md)
- [Forms](#forms) - [Forms](#forms)
- [HTTP Authentication](#http-authentication) - [HTTP Authentication](#http-authentication)
- [Custom HTTP Headers](#custom-http-headers) - [Custom HTTP Headers](#custom-http-headers)
- [Unix Domain Sockets](#unix-domain-sockets) - [Unix Domain Sockets](#unix-domain-sockets)
- [**All Available Options**](#requestoptions-callback) - [**All Available Options**](#requestoptions-callback)
## Extra Features
The following are features that the original `request` did not have, but have been added for convenience in `@root/request`.
- Support for `async`/`await` & `Promise`s (as explained above)
- `request({ userAgent: 'my-api/1.1' })` (for building API clients)
- `resp.ok` (just like `fetch`)
- `resp.stream` (see above)
See [EXTRA.md](/EXTRA.md)
## Forms ## Forms
`urequest` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. `@root/request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads.
<!-- For `multipart/related` refer to the `multipart` API. --> <!-- For `multipart/related` refer to the `multipart` API. -->
#### application/x-www-form-urlencoded (URL-Encoded Forms) #### application/x-www-form-urlencoded (URL-Encoded Forms)
@ -41,24 +149,29 @@ request('http://www.google.com', function (error, response, body) {
URL-encoded forms are simple. URL-encoded forms are simple.
```js ```js
request.post('http://service.com/upload', {form:{key:'value'}}) request.post('http://service.com/upload', { form: { key: 'value' } });
// or // or
request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ }) request.post(
{ url: 'http://service.com/upload', form: { key: 'value' } },
function (err, httpResponse, body) {
/* ... */
}
);
``` ```
<!-- <!--
// or // or
request.post('http://service.com/upload').form({key:'value'}) request.post('http://service.com/upload').form({key:'value'})
--> -->
#### multipart/form-data (Multipart Form Uploads) #### multipart/form-data (Multipart Form Uploads)
For `multipart/form-data` we use the [form-data](https://github.com/form-data/form-data) library by [@felixge](https://github.com/felixge). For the most cases, you can pass your upload form data via the `formData` option. For `multipart/form-data` we use the [form-data](https://github.com/form-data/form-data/tree/v2.5.1) library by [@felixge](https://github.com/felixge). For the most cases, you can pass your upload form data via the `formData` option.
To use `form-data`, you must install it separately: To use `form-data`, you must install it separately:
```bash ```bash
npm install --save form-data@2 npm install --save form-data@2.x
``` ```
```js ```js
@ -85,13 +198,17 @@ var formData = {
} }
} }
}; };
request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) { request.post(
{ url: 'http://service.com/upload', formData: formData },
function optionalCallback(err, httpResponse, body) {
if (err) { if (err) {
return console.error('upload failed:', err); return console.error('upload failed:', err);
} }
console.log('Upload successful! Server responded with:', body); console.log('Upload successful! Server responded with:', body);
}); }
);
``` ```
<!-- <!--
For advanced cases, you can access the form-data object itself via `r.form()`. This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling `form()` will clear the currently set form data for that request.) For advanced cases, you can access the form-data object itself via `r.form()`. This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling `form()` will clear the currently set form data for that request.)
@ -118,18 +235,19 @@ request.get('http://some.server.com/').auth('username', 'password', false);
request.get('http://some.server.com/').auth(null, null, true, 'bearerToken'); request.get('http://some.server.com/').auth(null, null, true, 'bearerToken');
// or // or
--> -->
```js ```js
request.get('http://some.server.com/', { request.get('http://some.server.com/', {
'auth': { auth: {
'user': 'username', user: 'username',
'pass': 'password', pass: 'password',
'sendImmediately': false sendImmediately: false
} }
}); });
// or // or
request.get('http://some.server.com/', { request.get('http://some.server.com/', {
'auth': { auth: {
'bearer': 'bearerToken' bearer: 'bearerToken'
} }
}); });
``` ```
@ -162,7 +280,7 @@ var username = 'username',
password = 'password', password = 'password',
url = 'http://' + username + ':' + password + '@some.server.com'; url = 'http://' + username + ':' + password + '@some.server.com';
request({url: url}, function (error, response, body) { request({ url: url }, function (error, response, body) {
// Do more stuff with 'body' here // Do more stuff with 'body' here
}); });
``` ```
@ -203,8 +321,8 @@ var options = {
function callback(error, response, body) { function callback(error, response, body) {
if (!error && response.statusCode == 200) { if (!error && response.statusCode == 200) {
var info = JSON.parse(body); var info = JSON.parse(body);
console.log(info.stargazers_count + " Stars"); console.log(info.stargazers_count + ' Stars');
console.log(info.forks_count + " Forks"); console.log(info.forks_count + ' Forks');
} }
} }
@ -217,11 +335,13 @@ request(options, callback);
## UNIX Domain Sockets ## UNIX Domain Sockets
`urequest` supports making requests to [UNIX Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme: `@root/request` supports making requests to [UNIX Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme:
```js ```js
/* Pattern */ 'http://unix:SOCKET:PATH' /* Pattern */ 'http://unix:SOCKET:PATH';
/* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path') /* Example */ request.get(
'http://unix:/absolute/path/to/unix.socket:/request/path'
);
``` ```
Note: The `SOCKET` path is assumed to be absolute to the root of the host file system. Note: The `SOCKET` path is assumed to be absolute to the root of the host file system.
@ -299,30 +419,31 @@ instead, it **returns a wrapper** that has your default settings applied to it.
`request.defaults` to add/override defaults that were previously defaulted. `request.defaults` to add/override defaults that were previously defaulted.
For example: For example:
```js ```js
//requests using baseRequest() will set the 'x-token' header //requests using baseRequest() will set the 'x-token' header
var baseRequest = request.defaults({ var baseRequest = request.defaults({
headers: {'x-token': 'my-token'} headers: { 'x-token': 'my-token' }
}) });
//requests using specialRequest() will include the 'x-token' header set in //requests using specialRequest() will include the 'x-token' header set in
//baseRequest and will also include the 'special' header //baseRequest and will also include the 'special' header
var specialRequest = baseRequest.defaults({ var specialRequest = baseRequest.defaults({
headers: {special: 'special value'} headers: { special: 'special value' }
}) });
``` ```
### request.METHOD() ### request.METHOD()
These HTTP method convenience functions act just like `request()` but with a default method already set for you: These HTTP method convenience functions act just like `request()` but with a default method already set for you:
- *request.get()*: Defaults to `method: "GET"`. - _request.get()_: Defaults to `method: "GET"`.
- *request.post()*: Defaults to `method: "POST"`. - _request.post()_: Defaults to `method: "POST"`.
- *request.put()*: Defaults to `method: "PUT"`. - _request.put()_: Defaults to `method: "PUT"`.
- *request.patch()*: Defaults to `method: "PATCH"`. - _request.patch()_: Defaults to `method: "PATCH"`.
- *request.del() / request.delete()*: Defaults to `method: "DELETE"`. - _request.del() / request.delete()_: Defaults to `method: "DELETE"`.
- *request.head()*: Defaults to `method: "HEAD"`. - _request.head()_: Defaults to `method: "HEAD"`.
- *request.options()*: Defaults to `method: "OPTIONS"`. - _request.options()_: Defaults to `method: "OPTIONS"`.
--- ---
@ -330,7 +451,7 @@ These HTTP method convenience functions act just like `request()` but with a def
There are at least <!--three--> two ways to debug the operation of `request`: There are at least <!--three--> two ways to debug the operation of `request`:
1. Launch the node process like `NODE_DEBUG=urequest node script.js` 1. Launch the node process like `NODE_DEBUG=@root/request node script.js`
(`lib,request,otherlib` works too). (`lib,request,otherlib` works too).
2. Set `require('@root/request').debug = true` at any time (this does the same thing 2. Set `require('@root/request').debug = true` at any time (this does the same thing

View File

@ -5,7 +5,9 @@ var request = require('../');
// will redirect to https://www.github.com and then https://github.com // will redirect to https://www.github.com and then https://github.com
//request('http://www.github.com', function (error, response, body) { //request('http://www.github.com', function (error, response, body) {
request({ uri: { protocol: 'http:', hostname: 'www.github.com' } }, function (error, response, body) { request(
{ uri: { protocol: 'http:', hostname: 'www.github.com' } },
function (error, response, body) {
if (error) { if (error) {
console.log('error:', error); // Print the error if one occurred console.log('error:', error); // Print the error if one occurred
return; return;
@ -13,4 +15,5 @@ request({ uri: { protocol: 'http:', hostname: 'www.github.com' } }, function (er
console.log('statusCode:', response.statusCode); // The final statusCode console.log('statusCode:', response.statusCode); // The final statusCode
console.log('Final href:', response.request.uri.href); // The final URI console.log('Final href:', response.request.uri.href); // The final URI
console.log('Body Length:', body.length); // body length console.log('Body Length:', body.length); // body length
}); }
);

View File

@ -9,15 +9,18 @@ var request = require('../');
//request('http://www.github.com', function (error, response, body) { //request('http://www.github.com', function (error, response, body) {
request( request(
//{ url: 'http://postb.in/syfxxnko' //{ url: 'http://postb.in/syfxxnko'
{ url: 'http://localhost:3007/form-data/' {
, method: 'POST' url: 'http://localhost:3007/form-data/',
, headers: { 'X-Foo': 'Bar' } method: 'POST',
, formData: { headers: { 'X-Foo': 'Bar' },
foo: 'bar' formData: {
, baz: require('fs').createReadStream(require('path').join(__dirname, 'get-to-json.js')) foo: 'bar',
baz: require('fs').createReadStream(
require('path').join(__dirname, 'get-to-json.js')
)
} }
} },
, function (error, response, body) { function (error, response, body) {
if (error) { if (error) {
console.log('error:', error); // Print the error if one occurred console.log('error:', error); // Print the error if one occurred
return; return;

View File

@ -4,7 +4,9 @@
var request = require('../'); var request = require('../');
// would normally redirect to https://www.github.com and then https://github.com // would normally redirect to https://www.github.com and then https://github.com
request({ uri: 'https://www.github.com', followRedirect: false }, function (error, response, body) { request(
{ uri: 'https://www.github.com', followRedirect: false },
function (error, response, body) {
if (error) { if (error) {
console.log('error:', error); // Print the error if one occurred console.log('error:', error); // Print the error if one occurred
return; return;
@ -13,4 +15,5 @@ request({ uri: 'https://www.github.com', followRedirect: false }, function (erro
console.log('statusCode:', response.statusCode); // Should be 301 or 302 console.log('statusCode:', response.statusCode); // Should be 301 or 302
console.log('Location:', response.headers.location); // The redirect console.log('Location:', response.headers.location); // The redirect
console.log('Body:', body || JSON.stringify(body)); console.log('Body:', body || JSON.stringify(body));
}); }
);

15
examples/postbin.js Normal file
View File

@ -0,0 +1,15 @@
'use strict';
var request = require('../');
request({
url: 'https://postb.in/1588134650162-6019286897499?hello=world'
//headers: { 'user-agent': false } // remove
//headers: { 'user-agent': 'test/1.0' } // overwrite
//userAgent: 'test/1.1' // add to the default
})
.then(function (resp) {
console.log(resp.body);
})
.catch(function (err) {
console.error(err);
});

View File

@ -0,0 +1,27 @@
'use strict';
var request = require('../');
async function main() {
var tpath = '/tmp/google-index.html';
var resp = await request({
url: 'https://google.com',
encoding: null,
stream: tpath
});
console.log('[Response Headers]');
console.log(resp.toJSON().headers);
//console.error(resp.headers, resp.body.byteLength);
await resp.stream;
console.log('[Response Body] written to', tpath);
}
main()
.then(function () {
console.log('Pass');
})
.catch(function (e) {
console.error('Fail');
console.error(e.stack);
});

34
examples/stream.js Normal file
View File

@ -0,0 +1,34 @@
'use strict';
var request = require('../');
async function main() {
var tpath = '/tmp/google-index.html';
var resp = await request({
url: 'https://google.com',
encoding: null,
stream: true
});
console.log('[Response Headers]');
console.log(resp.toJSON().headers);
resp.on('data', function (chunk) {
console.log('[Data]', chunk.byteLength);
});
resp.on('end', function (chunk) {
console.log('[End]');
});
//console.error(resp.headers, resp.body.byteLength);
await resp.stream;
console.log('[Close]');
}
main()
.then(function () {
console.log('Pass');
})
.catch(function (e) {
console.error('Fail');
console.error(e.stack);
});

View File

@ -8,12 +8,13 @@ var request = require('../');
// will redirect to https://www.github.com and then https://github.com // will redirect to https://www.github.com and then https://github.com
//request('http://www.github.com', function (error, response, body) { //request('http://www.github.com', function (error, response, body) {
request( request(
{ url: 'http://postb.in/2meyt50C' {
, method: 'POST' url: 'http://postb.in/2meyt50C',
, headers: { 'X-Foo': 'Bar' } method: 'POST',
, form: { foo: 'bar', baz: 'qux' } headers: { 'X-Foo': 'Bar' },
} form: { foo: 'bar', baz: 'qux' }
, function (error, response, body) { },
function (error, response, body) {
if (error) { if (error) {
console.log('error:', error); // Print the error if one occurred console.log('error:', error); // Print the error if one occurred
return; return;

456
index.js
View File

@ -3,6 +3,9 @@
var http = require('http'); var http = require('http');
var https = require('https'); var https = require('https');
var url = require('url'); var url = require('url');
var os = require('os');
var pkg = require('./package.json');
var fs = require('fs'); // only for streams
function debug() { function debug() {
if (module.exports.debug) { if (module.exports.debug) {
@ -21,7 +24,10 @@ function mergeOrDelete(defaults, updates) {
// CRDT probs... // CRDT probs...
if ('undefined' === typeof updates[key]) { if ('undefined' === typeof updates[key]) {
delete updates[key]; delete updates[key];
} else if ('object' === typeof defaults[key] && 'object' === typeof updates[key]) { } else if (
'object' === typeof defaults[key] &&
'object' === typeof updates[key]
) {
updates[key] = mergeOrDelete(defaults[key], updates[key]); updates[key] = mergeOrDelete(defaults[key], updates[key]);
} }
}); });
@ -44,7 +50,6 @@ function hasHeader(reqOpts, header) {
} }
function toJSONifier(keys) { function toJSONifier(keys) {
return function () { return function () {
var obj = {}; var obj = {};
var me = this; var me = this;
@ -61,13 +66,125 @@ function toJSONifier(keys) {
}; };
} }
function setupPipe(resp, opts) {
// make the response await-able
var resolve;
var reject;
var p = new Promise(function (_resolve, _reject) {
resolve = _resolve;
reject = _reject;
});
// or an existing write stream
if ('function' === typeof opts.stream.pipe) {
if (opts.debug) {
console.debug('[@root/request] stream piped');
}
resp.pipe(opts.stream);
}
resp.once('error', function (e) {
if (opts.debug) {
console.debug("[@root/request] stream 'error'");
console.error(e.stack);
}
resp.destroy();
if ('function' === opts.stream.destroy) {
opts.stream.destroy(e);
}
reject(e);
});
resp.once('end', function () {
if (opts.debug) {
console.debug("[@root/request] stream 'end'");
}
if ('function' === opts.stream.destroy) {
opts.stream.end();
// this will close the stream (i.e. sync to disk)
opts.stream.destroy();
}
});
resp.once('close', function () {
if (opts.debug) {
console.debug("[@root/request] stream 'close'");
}
resolve();
});
return p;
}
function handleResponse(resp, opts, cb) {
// body can be buffer, string, or json
if (null === opts.encoding) {
resp._body = [];
} else {
resp.body = '';
}
resp._bodyLength = 0;
resp.on('readable', function () {
var chunk;
while ((chunk = resp.read())) {
if ('string' === typeof resp.body) {
resp.body += chunk.toString(opts.encoding);
} else {
resp._body.push(chunk);
resp._bodyLength += chunk.length;
}
}
});
resp.once('end', function () {
if ('string' !== typeof resp.body) {
if (1 === resp._body.length) {
resp.body = resp._body[0];
} else {
resp.body = Buffer.concat(resp._body, resp._bodyLength);
}
resp._body = null;
}
if (opts.json && 'string' === typeof resp.body) {
// TODO I would parse based on Content-Type
// but request.js doesn't do that.
try {
resp.body = JSON.parse(resp.body);
} catch (e) {
// ignore
}
}
debug('\n[urequest] resp.toJSON():');
if (module.exports.debug) {
debug(resp.toJSON());
}
if (opts.debug) {
console.debug('[@root/request] Response Body:');
console.debug(resp.body);
}
cb(null, resp, resp.body);
});
}
function setDefaults(defs) { function setDefaults(defs) {
defs = defs || {}; defs = defs || {};
function urequestHelper(opts, cb) { function urequestHelper(opts, cb) {
debug("\n[urequest] processed options:"); debug('\n[urequest] processed options:');
debug(opts); debug(opts);
var req;
var finalOpts = {};
// allow specifying a file
if ('string' === typeof opts.stream) {
if (opts.debug) {
console.debug('[@root/request] creating file write stream');
}
try {
opts.stream = fs.createWriteStream(opts.stream);
} catch (e) {
cb(e);
return;
}
}
function onResponse(resp) { function onResponse(resp) {
var followRedirect; var followRedirect;
@ -79,15 +196,35 @@ function setDefaults(defs) {
}); });
followRedirect = opts.followRedirect; followRedirect = opts.followRedirect;
resp.toJSON = toJSONifier([ 'statusCode', 'body', 'headers', 'request' ]); // copied from WHATWG fetch
resp.ok = false;
if (resp.statusCode >= 200 && resp.statusCode < 300) {
resp.ok = true;
}
resp.toJSON = toJSONifier([
'statusCode',
'body',
'ok',
'headers',
'request'
]);
resp.request = req; resp.request = req;
resp.request.uri = url.parse(opts.url); resp.request.uri = url.parse(opts.url);
//resp.request.method = opts.method; //resp.request.method = opts.method;
resp.request.headers = finalOpts.headers; resp.request.headers = finalOpts.headers;
resp.request.toJSON = toJSONifier([ 'uri', 'method', 'headers' ]); resp.request.toJSON = toJSONifier(['uri', 'method', 'headers']);
if (opts.debug) {
console.debug('[@root/request] Response Headers:');
console.debug(resp.toJSON());
}
if (followRedirect && resp.headers.location && -1 !== [ 301, 302, 307, 308 ].indexOf(resp.statusCode)) { if (
followRedirect &&
resp.headers.location &&
-1 !== [301, 302, 307, 308].indexOf(resp.statusCode)
) {
debug('Following redirect: ' + resp.headers.location); debug('Following redirect: ' + resp.headers.location);
if ('GET' !== opts.method && !opts.followAllRedirects) { if ('GET' !== opts.method && !opts.followAllRedirects) {
followRedirect = false; followRedirect = false;
@ -104,8 +241,12 @@ function setDefaults(defs) {
if (!opts.followOriginalHttpMethod) { if (!opts.followOriginalHttpMethod) {
opts.method = 'GET'; opts.method = 'GET';
opts.body = null; opts.body = null;
delete opts.headers[getHeaderName(opts, 'Content-Length')]; delete opts.headers[
delete opts.headers[getHeaderName(opts, 'Transfer-Encoding')]; getHeaderName(opts, 'Content-Length')
];
delete opts.headers[
getHeaderName(opts, 'Transfer-Encoding')
];
} }
if (opts.removeRefererHeader && opts.headers) { if (opts.removeRefererHeader && opts.headers) {
delete opts.headers.referer; delete opts.headers.referer;
@ -116,47 +257,22 @@ function setDefaults(defs) {
return urequestHelper(opts, cb); return urequestHelper(opts, cb);
} }
} }
if (null === opts.encoding) {
resp._body = []; if (opts.stream) {
} else { resp.stream = setupPipe(resp, opts);
resp.body = ''; // can be string, buffer, or json... why not an async function too?
} resp.stream.body = async function () {
resp._bodyLength = 0; handleResponse(resp, opts, cb);
resp.on('data', function (chunk) { await resp.stream;
if ('string' === typeof resp.body) { return resp.body;
resp.body += chunk.toString(opts.encoding); };
} else { cb(null, resp);
resp._body.push(chunk); return;
resp._bodyLength += chunk.length;
}
});
resp.on('end', function () {
if ('string' !== typeof resp.body) {
if (1 === resp._body.length) {
resp.body = resp._body[0];
} else {
resp.body = Buffer.concat(resp._body, resp._bodyLength);
}
resp._body = null;
}
if (opts.json && 'string' === typeof resp.body) {
// TODO I would parse based on Content-Type
// but request.js doesn't do that.
try {
resp.body = JSON.parse(resp.body);
} catch(e) {
// ignore
}
} }
debug("\n[urequest] resp.toJSON():"); handleResponse(resp, opts, cb);
debug(resp.toJSON());
cb(null, resp, resp.body);
});
} }
var req;
var finalOpts = {};
var _body; var _body;
var MyFormData; var MyFormData;
var form; var form;
@ -164,7 +280,7 @@ function setDefaults(defs) {
var requester; var requester;
if (opts.body) { if (opts.body) {
if (true === opts.json) { if (true === opts.json && 'string' !== typeof opts.body) {
_body = JSON.stringify(opts.body); _body = JSON.stringify(opts.body);
} else { } else {
_body = opts.body; _body = opts.body;
@ -172,13 +288,20 @@ function setDefaults(defs) {
} else if (opts.json && true !== opts.json) { } else if (opts.json && true !== opts.json) {
_body = JSON.stringify(opts.json); _body = JSON.stringify(opts.json);
} else if (opts.form) { } else if (opts.form) {
_body = Object.keys(opts.form).filter(function (key) { _body = Object.keys(opts.form)
.filter(function (key) {
if ('undefined' !== typeof opts.form[key]) { if ('undefined' !== typeof opts.form[key]) {
return true; return true;
} }
}).map(function (key) { })
return encodeURIComponent(key) + '=' + encodeURIComponent(String(opts.form[key])); .map(function (key) {
}).join('&'); return (
encodeURIComponent(key) +
'=' +
encodeURIComponent(String(opts.form[key]))
);
})
.join('&');
opts.headers['Content-Type'] = 'application/x-www-form-urlencoded'; opts.headers['Content-Type'] = 'application/x-www-form-urlencoded';
} }
if ('string' === typeof _body) { if ('string' === typeof _body) {
@ -192,43 +315,77 @@ function setDefaults(defs) {
// A bug should be raised if request does it differently, // A bug should be raised if request does it differently,
// but I think we're supposed to pass all acceptable options // but I think we're supposed to pass all acceptable options
// on to the raw http request // on to the raw http request
[ 'family', 'host', 'localAddress', 'agent', 'createConnection' [
, 'timeout', 'setHost' 'family',
'host',
'localAddress',
'agent',
'createConnection',
'timeout',
'setHost'
].forEach(function (key) { ].forEach(function (key) {
finalOpts[key] = opts.uri[key]; if (key in opts) {
finalOpts[key] = opts[key];
}
}); });
finalOpts.method = opts.method; finalOpts.method = opts.method;
finalOpts.headers = JSON.parse(JSON.stringify(opts.headers)); finalOpts.headers = JSON.parse(JSON.stringify(opts.headers));
var uaHeader = getHeaderName(finalOpts, 'User-Agent') || 'User-Agent';
// set a default user-agent
if (!finalOpts.headers[uaHeader]) {
if (false === finalOpts.headers[uaHeader]) {
delete finalOpts.headers[uaHeader];
} else {
finalOpts.headers[uaHeader] = getUserAgent(opts.userAgent);
}
}
if (_body) { if (_body) {
// Most APIs expect (or require) Content-Length except in the case of multipart uploads // Most APIs expect (or require) Content-Length except in the case of multipart uploads
// Transfer-Encoding: Chunked (the default) is generally only well-supported downstream // Transfer-Encoding: Chunked (the default) is generally only well-supported downstream
finalOpts.headers['Content-Length'] = _body.byteLength || _body.length; if (
'undefined' !== typeof _body.byteLength ||
'undefined' !== typeof _body.length
) {
finalOpts.headers['Content-Length'] =
_body.byteLength || _body.length;
}
} }
if (opts.auth) { if (opts.auth) {
// if opts.uri specifies auth it will be parsed by url.parse and passed directly to the http module // if opts.uri specifies auth it will be parsed by url.parse and passed directly to the http module
if ('string' !== typeof opts.auth) { if ('string' !== typeof opts.auth) {
opts.auth = (opts.auth.user||opts.auth.username||'') + ':' + (opts.auth.pass||opts.auth.password||''); opts.auth =
(opts.auth.user || opts.auth.username || '') +
':' +
(opts.auth.pass || opts.auth.password || '');
} }
if ('string' === typeof opts.auth) { if ('string' === typeof opts.auth) {
finalOpts.auth = opts.auth; finalOpts.auth = opts.auth;
} }
if (false === opts.sendImmediately) { if (false === opts.sendImmediately) {
console.warn("[Warn] setting `sendImmediately: false` is not yet supported. Please open an issue if this is an important feature that you need."); console.warn(
'[Warn] setting `sendImmediately: false` is not yet supported. Please open an issue if this is an important feature that you need.'
);
} }
if (opts.bearer) { // [request-compat]
if (opts.auth.bearer) {
// having a shortcut for base64 encoding makes sense, but this? Eh, whatevs... // having a shortcut for base64 encoding makes sense, but this? Eh, whatevs...
finalOpts.header.Authorization = 'Bearer: ' + opts.bearer; finalOpts.header.Authorization = 'Bearer ' + opts.auth.bearer;
} }
} }
if (opts.formData) { if (opts.formData) {
try { try {
MyFormData = opts.FormData || require('form-data'); MyFormData = opts.FormData || require('form-data');
// potential options https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15 // potential options https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15
} catch(e) { } catch (e) {
console.error("urequest does not include extra dependencies by default"); console.error(
console.error("if you need to use 'form-data' you may install it, like so:"); 'urequest does not include extra dependencies by default'
console.error(" npm install --save form-data"); );
console.error(
"if you need to use 'form-data' you may install it, like so:"
);
console.error(' npm install --save form-data');
cb(e); cb(e);
return; return;
} }
@ -236,7 +393,10 @@ function setDefaults(defs) {
form = new MyFormData(); form = new MyFormData();
Object.keys(opts.formData).forEach(function (key) { Object.keys(opts.formData).forEach(function (key) {
function add(key, data, opts) { function add(key, data, opts) {
if (data.value) { opts = data.options; data = data.value; } if (data.value) {
opts = data.options;
data = data.value;
}
form.append(key, data, opts); form.append(key, data, opts);
} }
if (Array.isArray(opts.formData[key])) { if (Array.isArray(opts.formData[key])) {
@ -247,7 +407,7 @@ function setDefaults(defs) {
add(key, opts.formData[key]); add(key, opts.formData[key]);
} }
}); });
} catch(e) { } catch (e) {
cb(e); cb(e);
return; return;
} }
@ -260,12 +420,12 @@ function setDefaults(defs) {
// TODO support unix sockets // TODO support unix sockets
if ('https:' === finalOpts.protocol) { if ('https:' === finalOpts.protocol) {
// https://nodejs.org/api/https.html#https_https_request_options_callback // https://nodejs.org/api/https.html#https_https_request_options_callback
debug("\n[urequest] https.request(opts):"); debug('\n[urequest] https.request(opts):');
debug(finalOpts); debug(finalOpts);
requester = https; requester = https;
} else if ('http:' === finalOpts.protocol) { } else if ('http:' === finalOpts.protocol) {
// https://nodejs.org/api/http.html#http_http_request_options_callback // https://nodejs.org/api/http.html#http_http_request_options_callback
debug("\n[urequest] http.request(opts):"); debug('\n[urequest] http.request(opts):');
debug(finalOpts); debug(finalOpts);
requester = http; requester = http;
} else { } else {
@ -279,7 +439,10 @@ function setDefaults(defs) {
// generally uploads don't use Chunked Encoding (some systems have issues with it) // generally uploads don't use Chunked Encoding (some systems have issues with it)
// and I don't want to do the work to calculate the content-lengths. This seems to work. // and I don't want to do the work to calculate the content-lengths. This seems to work.
req = form.submit(finalOpts, function (err, resp) { req = form.submit(finalOpts, function (err, resp) {
if (err) { cb(err); return; } if (err) {
cb(err);
return;
}
onResponse(resp); onResponse(resp);
resp.resume(); resp.resume();
}); });
@ -289,16 +452,37 @@ function setDefaults(defs) {
return; return;
} }
if (opts.debug) {
console.debug('');
console.debug('[@root/request] Request Options:');
console.debug(finalOpts);
if (_body) {
console.debug('[@root/request] Request Body:');
console.debug(
opts.body || opts.form || opts.formData || opts.json
);
}
}
req = requester.request(finalOpts, onResponse); req = requester.request(finalOpts, onResponse);
req.on('error', cb); req.once('error', cb);
if (_body) { if (_body) {
debug("\n[urequest] '" + finalOpts.method + "' (request) body"); debug("\n[urequest] '" + finalOpts.method + "' (request) body");
debug(_body); debug(_body);
if ('function' === typeof _body.pipe) {
// used for chunked encoding // used for chunked encoding
//req.write(_body); _body.pipe(req);
_body.once('error', function (err) {
// https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
// if the Readable stream emits an error during processing,
// the Writable destination is not closed automatically
_body.destroy();
req.destroy(err);
});
} else {
// used for known content-length // used for known content-length
req.end(_body); req.end(_body);
}
} else { } else {
req.end(); req.end();
} }
@ -307,14 +491,14 @@ function setDefaults(defs) {
function parseUrl(str) { function parseUrl(str) {
var obj = url.parse(str); var obj = url.parse(str);
var paths; var paths;
if ('unix' !== (obj.hostname||obj.host||'').toLowerCase()) { if ('unix' !== (obj.hostname || obj.host || '').toLowerCase()) {
return obj; return obj;
} }
obj.href = null; obj.href = null;
obj.hostname = obj.host = null; obj.hostname = obj.host = null;
paths = (obj.pathname||obj.path||'').split(':'); paths = (obj.pathname || obj.path || '').split(':');
obj.socketPath = paths.shift(); obj.socketPath = paths.shift();
obj.pathname = obj.path = paths.join(':'); obj.pathname = obj.path = paths.join(':');
@ -323,7 +507,7 @@ function setDefaults(defs) {
} }
function urequest(opts, cb) { function urequest(opts, cb) {
debug("\n[urequest] received options:"); debug('\n[urequest] received options:');
debug(opts); debug(opts);
var reqOpts = {}; var reqOpts = {};
// request.js behavior: // request.js behavior:
@ -364,7 +548,12 @@ function setDefaults(defs) {
} }
} }
if (opts.body || 'string' === typeof opts.json || opts.form || opts.formData) { if (
opts.body ||
(opts.json && true !== opts.json) ||
opts.form ||
opts.formData
) {
// TODO this is probably a deviation from request's API // TODO this is probably a deviation from request's API
// need to check and probably eliminate it // need to check and probably eliminate it
reqOpts.method = (reqOpts.method || 'POST').toUpperCase(); reqOpts.method = (reqOpts.method || 'POST').toUpperCase();
@ -377,59 +566,120 @@ function setDefaults(defs) {
// crazy case for easier testing // crazy case for easier testing
if (!hasHeader(reqOpts, 'CoNTeNT-TyPe')) { if (!hasHeader(reqOpts, 'CoNTeNT-TyPe')) {
if ((true === reqOpts.json && reqOpts.body) if (
|| (true !== reqOpts.json && reqOpts.json)) { (true === reqOpts.json && reqOpts.body) ||
(true !== reqOpts.json && reqOpts.json)
) {
reqOpts.headers['Content-Type'] = 'application/json'; reqOpts.headers['Content-Type'] = 'application/json';
} }
} }
if (opts.debug) {
reqOpts.debug = opts.debug;
}
return urequestHelper(reqOpts, cb); return urequestHelper(reqOpts, cb);
} }
urequest.defaults = function (_defs) { function smartPromisify(fn) {
return function (opts) {
var cb;
if ('function' === typeof arguments[1]) {
cb = Array.prototype.slice.call(arguments)[1];
return fn(opts, cb);
}
return new Promise(function (resolve, reject) {
fn(opts, function (err, resp) {
if (err) {
err._response = resp;
reject(err);
return;
}
resolve(resp);
});
});
};
}
var smartUrequest = smartPromisify(urequest);
smartUrequest.defaults = function (_defs) {
_defs = mergeOrDelete(defs, _defs); _defs = mergeOrDelete(defs, _defs);
return setDefaults(_defs); return setDefaults(_defs);
}; };
[ 'get', 'put', 'post', 'patch', 'delete', 'head', 'options' ].forEach(function (method) { ['get', 'put', 'post', 'patch', 'delete', 'head', 'options'].forEach(
urequest[method] = function (obj, cb) { function (method) {
smartUrequest[method] = smartPromisify(function (obj, cb) {
if ('string' === typeof obj) { if ('string' === typeof obj) {
obj = { url: obj }; obj = { url: obj };
} }
obj.method = method.toUpperCase(); obj.method = method.toUpperCase();
urequest(obj, cb); urequest(obj, cb);
};
}); });
urequest.del = urequest.delete; }
);
smartUrequest.del = urequest.delete;
return urequest; return smartUrequest;
}
var nodeUa =
'@root+request/' +
pkg.version +
' ' +
process.release.name +
'/' +
process.version +
' ' +
os.platform() +
'/' +
os.release() +
' ' +
os.type() +
'/' +
process.arch;
function getUserAgent(additional) {
// See https://tools.ietf.org/html/rfc8555#section-6.1
// And https://tools.ietf.org/html/rfc7231#section-5.5.3
// And https://community.letsencrypt.org/t/user-agent-flag-explained/3843/2
var ua = nodeUa;
if (additional) {
ua = additional + ' ' + ua;
}
return ua;
} }
var _defaults = { var _defaults = {
sendImmediately: true sendImmediately: true,
, method: 'GET' method: '',
, headers: {} headers: {},
, useQuerystring: false useQuerystring: false,
, followRedirect: true followRedirect: true,
, followAllRedirects: false followAllRedirects: false,
, followOriginalHttpMethod: false followOriginalHttpMethod: false,
, maxRedirects: 10 maxRedirects: 10,
, removeRefererHeader: false removeRefererHeader: false,
//, encoding: undefined // encoding: undefined,
, gzip: false // stream: false, // TODO allow a stream?
//, body: undefined gzip: false
//, json: undefined //, body: undefined
//, json: undefined
}; };
module.exports = setDefaults(_defaults); module.exports = setDefaults(_defaults);
module.exports._keys = Object.keys(_defaults).concat([ module.exports._keys = Object.keys(_defaults).concat([
'encoding' 'encoding',
, 'body' 'stream',
, 'json' 'body',
, 'form' 'json',
, 'auth' 'form',
, 'formData' 'auth',
, 'FormData' 'formData',
'FormData',
'userAgent' // non-standard for request.js
]); ]);
module.exports.debug = (-1 !== (process.env.NODE_DEBUG||'').split(/\s+/g).indexOf('urequest')); module.exports.debug =
-1 !== (process.env.NODE_DEBUG || '').split(/\s+/g).indexOf('urequest');
debug("DEBUG ON for urequest"); debug('DEBUG ON for urequest');

5
package-lock.json generated Normal file
View File

@ -0,0 +1,5 @@
{
"name": "@root/request",
"version": "1.8.2",
"lockfileVersion": 1
}

View File

@ -1,6 +1,6 @@
{ {
"name": "@root/request", "name": "@root/request",
"version": "1.3.11", "version": "1.8.2",
"description": "A lightweight, zero-dependency drop-in replacement for request", "description": "A lightweight, zero-dependency drop-in replacement for request",
"main": "index.js", "main": "index.js",
"files": [ "files": [
@ -24,6 +24,6 @@
"https", "https",
"call" "call"
], ],
"author": "AJ ONeal <solderjs@gmail.com> (https://solderjs.com/)", "author": "AJ ONeal <coolaj86@gmail.com> (https://coolaj86.com/)",
"license": "(MIT OR Apache-2.0)" "license": "(MIT OR Apache-2.0)"
} }

View File

@ -5,7 +5,7 @@ var server = net.createServer(function (socket) {
socket.on('data', function (chunk) { socket.on('data', function (chunk) {
console.info(chunk.toString('utf8')); console.info(chunk.toString('utf8'));
}); });
}) });
server.listen(3007, function () { server.listen(3007, function () {
console.info("Listening on", this.address()); console.info('Listening on', this.address());
}); });