forked from node-modules/urllib-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (70 loc) · 1.65 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
/*!
* urllib-sync - index.js
* Copyright(c) 2014 dead_horse <[email protected]>
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
*/
var cp = require('child_process');
var utility = require('utility');
var assert = require('assert');
var path = require('path');
var fs = require('fs');
assert(cp.spawnSync, 'urllib-sync need node version 0.11.13+');
exports.request = function request(url, args) {
assert(url, 'url required');
args = args || {};
var input = utility.base64encode(JSON.stringify({
url: url,
args: args
}));
var requestPath = path.join(__dirname, './request.js');
var cmd = process.execPath;
var _args = [requestPath, input];
var res = cp.spawnSync(cmd, _args, {
timeout: (args.timeout || 3000) + 1000
});
if (res.error) {
res.error.url = url;
res.error.args = args;
throw res.error;
}
if (res.status !== 0) {
var e = new Error(res.stderr.toString() || 'unknown error');
e.url = url;
e.args = args;
e.status = res.status;
throw e;
}
try {
res = JSON.parse(res.stdout);
} catch (err) {
var e = new Error('parse response error:' + err.message);
e.url = url;
e.args = args;
throw e;
}
try {
switch (res.type) {
case 'string':
res.data = fs.readFileSync(res.path).toString();
break;
case 'json':
res.data = JSON.parse(fs.readFileSync(res.path).toString());
break;
case 'file':
res.data = null;
break;
default:
res.data = fs.readFileSync(res.path);
}
} catch (err){
// ignore
} finally {
if (res.type !== 'file') fs.unlinkSync(res.path);
delete res.path;
}
return res;
};