get-body-size.js 644 B

1234567891011121314151617181920212223242526272829303132
  1. 'use strict';
  2. const fs = require('fs');
  3. const util = require('util');
  4. const is = require('@sindresorhus/is');
  5. const isFormData = require('./is-form-data');
  6. module.exports = async options => {
  7. const {body} = options;
  8. if (options.headers['content-length']) {
  9. return Number(options.headers['content-length']);
  10. }
  11. if (!body && !options.stream) {
  12. return 0;
  13. }
  14. if (is.string(body)) {
  15. return Buffer.byteLength(body);
  16. }
  17. if (isFormData(body)) {
  18. return util.promisify(body.getLength.bind(body))();
  19. }
  20. if (body instanceof fs.ReadStream) {
  21. const {size} = await util.promisify(fs.stat)(body.path);
  22. return size;
  23. }
  24. return null;
  25. };