forked from node-js-libs/curlrequest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
435 lines (392 loc) · 12.3 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
var util = require('util')
, fs = require('fs')
, tmp = require('tmp')
, spawn = require('./spawn')
, errors = require('./errors')
, cwd = process.cwd();
/**
* Make some curl opts friendlier.
*/
var curl_map = {
timeout: 'max-time'
, redirects: 'max-redirs'
, method: 'request'
, useragent: 'user-agent'
};
/**
* Default user-agents.
*/
var user_agents = require('./useragents.js')
, user_agents_len = user_agents.length;
/**
* Make a request with cURL.
*
* @param {Object|String} options (optional) - see `man curl`
* @param {Function} callback (optional)
* @api public
*/
exports.request = function (options, callback) {
if (arguments.length === 1) {
var defaults = options;
return function (options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
} else if (typeof options === 'string') {
options = { url: options };
}
for (var key in defaults) {
if (typeof options[key] === 'undefined') {
options[key] = defaults[key];
}
}
exports.request.call(this, options, callback);
};
}
if (options.retries) {
var remaining = options.retries;
delete options.retries;
return (function curl() {
exports.request(options, function (err) {
if (!err || !--remaining) {
return callback.apply(this, arguments);
}
process.nextTick(curl);
});
})();
}
if (typeof options === 'string') {
options = { url: options };
} else {
options = exports.copy(options);
}
for (var key in curl_map) {
if (typeof options[key] !== 'undefined') {
options[curl_map[key]] = options[key];
delete options[key];
}
}
var curl
, curl_path = 'curl'
, args = ['--silent', '--show-error', '--no-buffer', '--globoff']
, start = new Date
, err
, stderr = ''
, stdoutlen
, stdout = new Buffer(stdoutlen = 0)
, encoding
, complete
, cleanup
, postprocess
, require_str
, require_not_str
, scope = {}
, cmd = 'curl'
, detailsFilename = ''
, timeout;
function parseHeaders(filename) {
var headerText = fs.readFileSync(filename, 'utf-8');
var parts = headerText.split('\r\n');
var headerParts;
var response = {statusCode: null, headers: {}, body: null};
for (var i=0; i < parts.length; i++) {
if (parts[i].startsWith('HTTP')) {
response.statusCode = parseInt(parts[i].split(' ')[1]);
response.headers = {};
inHeaders = true;
} else if (!parts[i].trim()) {
continue;
} else {
headerParts = parts[i].split(':');
response.headers[headerParts[0].trim()] = headerParts.splice(1).join(':').trim();
}
}
fs.unlinkSync(filename);
return response;
}
function finish() {
if (options.fail && stderr) {
err = String(stderr).replace(/^curl: \(\d+\) /, ''); // "curl: (22) The requested URL returned error..." => "The requested URL returned error..."
} else if (err in errors) {
err = errors[err];
}
if (detailsFilename) {
var response = parseHeaders(detailsFilename);
response.body = stdout;
callback.call(scope, err, response, {
cmd: cmd
, args: args
, time: (new Date().getTime() - start.getTime())
});
} else {
callback.call(scope, err, stdout, {
cmd: cmd
, args: args
, time: (new Date().getTime() - start.getTime())
});
}
complete = true;
}
//Allow for a custom curl path
if (options.curl_path) {
curl_path = options.curl_path;
delete options.curl_path;
}
//Set the maximum number of retries to 3 by default
if (options['max-redirs'] === undefined) {
options['max-redirs'] = 3;
}
//Follow location by default
if (options.location === false) {
delete options.location;
} else {
options.location = true;
}
// Implement details
if (options.details) {
detailsFilename = tmp.tmpNameSync({ prefix: 'curlrequest-headers-' });
options['dump-header'] = detailsFilename;
delete options.details;
delete options.include;
}
//Add an additional setTimeout for max-time
if (options['max-time']) {
timeout = setTimeout(function () {
if (complete) return;
stderr = 'timeout', stdout = null;
finish();
if (curl && curl.kill) curl.kill('SIGKILL');
}, 1000 * options['max-time']);
}
//Default encoding is utf8. Set encoding = null to get a buffer
if (!options.encoding && options.encoding !== null) {
options.encoding = 'utf8';
}
encoding = options.encoding;
if (encoding === 'ascii') {
options['use-ascii'] = true;
}
delete options.encoding;
//Parse POST data
if (options.data && typeof options.data === 'object') {
var data = [];
for (var key in options.data) {
data.push(encodeURIComponent(key) + '=' + encodeURIComponent(options.data[key]));
}
options.data = data.join('&');
}
//Check for the occurrence of a string and fail if not found
if (options.require) {
require_str = options.require;
if (!Array.isArray(require_str)) {
require_str = [require_str];
}
delete options.require;
}
//Check for the occurrence of a string and fail if found
if (options.require_not) {
require_not_str = options.require_not;
if (!Array.isArray(require_not_str)) {
require_not_str = [require_not_str];
}
delete options.require_not;
}
//Call the callback in a custom scope
if (options.scope) {
scope = options.scope;
delete options.scope;
}
//Apply a post-processing function?
if (options.process) {
postprocess = options.process;
delete options.process;
}
//Setup default headers
var key, headers = {};
if (options.headers) {
var normalised_key;
for (key in options.headers) {
normalised_key = key.replace(/[_-]/g, ' ').split(' ').map(function (str) {
if (str.length) {
str = str[0].toUpperCase() + str.substr(1);
}
return str;
}).join('-');
headers[normalised_key] = options.headers[key];
}
delete options.headers;
}
options.header = options.header || [];
for (key in headers) {
options.header.push(key + ': ' + headers[key]);
}
//Select a random user agent if user-agent is set to true
if (options['user-agent'] === true) {
options['user-agent'] = user_agents[Math.random() * user_agents_len | 0];
}
//Prepare curl args
var key, values;
for (key in options) {
if (key === 'pretend') {
continue;
}
values = Array.isArray(options[key]) ? options[key] : [options[key]];
values.forEach(function (value) {
args.push('--' + key);
if (true !== value) {
args.push(value);
}
});
}
if (options.file) {
cmd = 'cat';
args = [options.file];
}
//Simulate the spawn?
if (options.pretend) {
return finish();
}
//Spawn the process
var child = spawn(cmd, args, { cwd: options.cwd || cwd }, function (curl) {
//Collect stdout
curl.stdout.on('data', function (data) {
if (complete) return;
var len = data.length, prev = stdout;
stdout = new Buffer(len + stdoutlen);
prev.copy(stdout, 0, 0, stdoutlen);
data.copy(stdout, stdoutlen, 0, len);
stdoutlen += len;
});
//Pipe stderr to the current process?
if (options.stderr) {
if (options.stderr === true) {
curl.stderr.pipe(process.stderr);
delete options.stderr
}
}
curl.stderr.on('data', function (data) {
if (complete) return;
stderr += data;
});
//Handle curl exit
curl.on('close', function (code) {
try {
err = code;
if (complete) return;
if (encoding) {
stdout = stdout.toString(encoding);
}
if (postprocess && stdout) {
stdout = postprocess(stdout);
}
if (require_str) {
var valid = false;
if (!encoding) {
stdout = stdout.toString();
}
var str;
for (var i = 0, l = require_str.length; i < l; i++) {
str = require_str[i];
if ((util.isRegExp(str) && str.test(stdout)) || stdout.indexOf(str) !== -1) {
valid = true;
break;
}
}
if (!valid) {
err = 'response does not contain required string: ' + str;
stdout = null
} else if (!encoding) {
stdout = new Buffer(stdout);
}
}
if (require_not_str) {
var valid = true;
if (!encoding) {
stdout = stdout.toString();
}
var str;
for (var i = 0, l = require_not_str.length; i < l; i++) {
str = require_not_str[i];
if ((util.isRegExp(str) && str.test(stdout)) || stdout.indexOf(str) !== -1) {
valid = false;
break;
}
}
if (!valid) {
err = 'response contains bad string: ' + str;
stdout = null
} else if (!encoding) {
stdout = new Buffer(stdout);
}
}
} catch (e) {
err = typeof e === 'object' ? e.message || '' : e;
}
finish();
if (timeout) clearTimeout(timeout);
});
});
};
/**
* Expose a helper for scraping urls from a page.
*/
var urls = /(?:href|src|HREF|SRC)=["']?([^"' >]+)/g;
exports.urls = function (data, regex) {
var match, matches = [];
while (match = urls.exec(data)) {
if (regex && !regex.test(match[1])) {
continue;
}
matches.push(match[1].replace(/[\r\n\t\s]/g, ''));
}
return matches;
};
/**
* A helper for handling async concurrency.
*/
exports.concurrent = function (input, concurrency, fn) {
if (arguments.length === 3) {
var len = input.length, pos = 0, remaining = concurrency;
for (var i = 0; i < concurrency; i++) {
(function exec() {
if (pos >= len) {
if (!--remaining) {
fn(null, function () {});
}
} else {
fn(input[pos++], function () {
process.nextTick(exec);
});
}
})();
}
} else {
fn = concurrency;
concurrency = input;
for (var i = 0; i < concurrency; i++) {
(function exec() {
fn(function () {
process.nextTick(exec);
});
})();
}
}
};
/**
* A helper for copying an object.
*/
exports.copy = function (obj) {
var copy = {};
for (var i in obj) {
if (Array.isArray(obj[i])) {
copy[i] = obj[i].map(function (item) {
return item;
});
} else if (typeof obj[i] === 'object') {
copy[i] = obj[i] ? exports.copy(obj[i]) : null;
} else {
copy[i] = obj[i];
}
}
return copy;
};