-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
103 lines (86 loc) · 2.51 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
102
103
/**
* http-post
*
* (c) copyright 2012 Sam Thompson <[email protected]>
* License: The MIT License - http://opensource.org/licenses/mit-license.php
*/
module.exports = function(options, data, files, fn) {
if (typeof(files) == 'function' || typeof(files) == 'undefined') {
fn = files;
files = [];
}
if (typeof(fn) != 'function') {
fn = function() {};
}
if (typeof(options) == 'string') {
var options = require('url').parse(options);
}
var fs = require('fs');
var endl = "\r\n";
var length = 0;
var contentType = '';
// If we have files, we have to chose multipart, otherweise we just stringify the query
if (files.length) {
var boundary = '-----np' + Math.random();
var toWrite = [];
for(var k in data) {
toWrite.push('--' + boundary + endl);
toWrite.push('Content-Disposition: form-data; name="' + k + '"' + endl);
toWrite.push(endl);
toWrite.push(data[k] + endl);
}
var name = '', stats;
for (var k in files) {
if (fs.existsSync(files[k].path)) {
// Determine the name
name = (typeof(files[k].name) == 'string') ? files[k].name : files[k].path.replace(/\\/g,'/').replace( /.*\//, '' );
// Determine the size and store it in our files area
stats = fs.statSync(files[k].path);
files[k].length = stats.size;
toWrite.push('--' + boundary + endl);
toWrite.push('Content-Disposition: form-data; name="' + files[k].param + '"; filename="' + name + '"' + endl);
//toWrite.push('Content-Type: image/png');
toWrite.push(endl);
toWrite.push(files[k]);
}
}
// The final multipart terminator
toWrite.push('--' + boundary + '--' + endl);
// Now that toWrite is filled... we need to determine the size
for(var k in toWrite) {
length += toWrite[k].length;
}
contentType = 'multipart/form-data; boundary=' + boundary;
}
else {
data = require('querystring').stringify(data);
length = data.length;
contentType = 'application/x-www-form-urlencoded';
}
options.method = 'POST';
options.headers = {
'Content-Type': contentType,
'Content-Length': length
};
var req = require('http').request(options, function(responce) {
fn(responce);
});
// Multipart and form-urlencded work slightly differnetly for sending
if (files.length) {
for(var k in toWrite) {
if (typeof(toWrite[k]) == 'string') {
req.write(toWrite[k]);
}
else {
// @todo make it work better for larger files
req.write(fs.readFileSync(toWrite[k].path, 'binary'));
req.write(endl);
}
}
}
else {
req.write(data);
}
req.end();
return req;
}