Skip to content

Commit

Permalink
Set content-length automatically for fs.createReadStream
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed May 1, 2018
1 parent 00fdeea commit 6e7a455
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 4 deletions.
8 changes: 6 additions & 2 deletions index.js
Expand Up @@ -253,10 +253,14 @@ function requestAsEventEmitter(opts) {
try {
uploadBodySize = await getBodySize(opts);

// This is the second try at setting a `content-length` header.
// This supports getting the size async, in contrast to
// https://github.com/sindresorhus/got/blob/82763c8089596dcee5eaa7f57f5dbf8194842fe6/index.js#L579-L582
// TODO: We should unify these two at some point
if (
uploadBodySize > 0 &&
is.undefined(opts.headers['content-length']) &&
is.undefined(opts.headers['transfer-encoding']) &&
isFormData(opts.body)
is.undefined(opts.headers['transfer-encoding'])
) {
opts.headers['content-length'] = uploadBodySize;
}
Expand Down
4 changes: 2 additions & 2 deletions readme.md
Expand Up @@ -114,15 +114,15 @@ Returns a `Stream` instead of a `Promise`. This is equivalent to calling `got.st

###### body

Type: `string` `Buffer` `stream.Readable`
Type: `string` `Buffer` `stream.Readable` [`form-data` instance](https://github.com/form-data/form-data)

*This is mutually exclusive with stream mode.*

Body that will be sent with a `POST` request.

If present in `options` and `options.method` is not set, `options.method` will be set to `POST`.

If `content-length` or `transfer-encoding` is not set in `options.headers` and `body` is a string or buffer, `content-length` will be set to the body length.
The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / `fs.createReadStream` instance / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`.

###### encoding

Expand Down
1 change: 1 addition & 0 deletions test/fixtures/stream-content-length
@@ -0,0 +1 @@
Unicorns
10 changes: 10 additions & 0 deletions test/headers.js
@@ -1,3 +1,5 @@
import fs from 'fs';
import path from 'path';
import test from 'ava';
import FormData from 'form-data';
import got from '..';
Expand Down Expand Up @@ -115,6 +117,14 @@ test('form-data sets content-length', async t => {
t.is(headers['content-length'], '157');
});

test('stream as options.body sets content-length', async t => {
const {body} = await got(s.url, {
body: fs.createReadStream(path.join(__dirname, 'fixtures/stream-content-length'))
});
const headers = JSON.parse(body);
t.is(headers['content-length'], '9');
});

test('remove null value headers', async t => {
const {body} = await got(s.url, {
headers: {
Expand Down

0 comments on commit 6e7a455

Please sign in to comment.