-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
101 lines (91 loc) · 2.04 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
var fs = require('fs')
var stream = require('stream')
function sync (body) {
var length = 0
if (typeof body === 'string') {
length = Buffer.byteLength(body)
}
else if (Array.isArray(body)) {
length = body.reduce(function (a, b) {return a + b.length}, 0)
}
else if (Buffer.isBuffer(body)) {
length = body.length
}
return length
}
function async (body, done) {
_async(body, function (err, length) {
if (err) {
done(err)
}
else if (!length) {
done(new Error('Content length not available'))
}
else {
done(null, parseInt(length))
}
})
}
function _async (body, done) {
// file stream
if (body.hasOwnProperty('fd')) {
fs.stat(body.path, function (err, stats) {
done(err, stats.size)
})
}
// http response
else if (body.hasOwnProperty('httpVersion')) {
done(null, body.headers['content-length'])
}
// request
else if (body.hasOwnProperty('httpModule')) {
body.on('response', function (res) {
done(null, res.headers['content-length'])
})
}
// @request/core
else if (body.hasOwnProperty('_client')) {
body.on('response', function (res) {
done(null, res.headers.get('content-length'))
})
}
else {
done(new Error('Content length not available'))
}
}
// @request/multipart
function multipart (body, done) {
var length = 0, streams = []
body._items.forEach(function (item) {
length += sync(item)
if (item instanceof stream.Stream) {
streams.push(item)
}
})
if (!streams.length) return done(null, length)
var ready = 0, error
streams.forEach(function (stream) {
handle(stream, function (err, len) {
if (err) {
error = err
}
else {
length += len
}
if (++ready === streams.length) {
done(error, length)
}
})
})
function handle (stream, done) {
if (stream._knownLength) {
done(null, stream._knownLength)
}
else {
async(stream, done)
}
}
}
exports.sync = sync
exports.async = async
exports.multipart = multipart