UNPKG

4.07 kBJavaScriptView Raw
1/**
2 * @fileoverview Http request in node.js
3 * @author douzi <liaowei08@gmail.com>
4 */
5var http = require('http');
6var util = require('utils-extend');
7var url = require('url');
8var path = require('path');
9var querystring = require('querystring');
10var file = require('file-system');
11
12/**
13 * @description
14 * http request
15 * @param {object|string} [options]
16 * @param {function} [callback]
17 * @example
18 * request('url', function(err, res, body) { });
19 * request({url: '', headers: {}, method: 'POST'}, function(err, res, body) { });
20 */
21function request(options, callback) {
22 var opts = {
23 headers: {
24 'Content-Type': 'application/json'
25 },
26 method: 'GET',
27 encoding: 'utf8',
28 // If the callback body is buffer, it can hanlder document pipe simply
29 isBuffer: false,
30 json: false
31 };
32
33 if (util.isString(options)) {
34 opts.url = options;
35 } else {
36 util.extend(opts, options);
37 }
38
39 // Append request data
40 if (opts.data) {
41 if (opts.method === 'GET') {
42 opts.url += '?' + querystring.stringify(opts.data);
43 } else {
44 opts.data = JSON.stringify(opts.data);
45 opts.headers['Content-Length'] = opts.data.length;
46 }
47 }
48
49 // Extend request url object
50 util.extend(opts, util.pick(url.parse(opts.url), 'hostname', 'port', 'path', 'auth'));
51 delete opts.url;
52
53 var req = http.request(opts, function(res) {
54 var body = [];
55 var size = 0;
56
57 res.on('data', function(chunk) {
58 body.push(chunk);
59 size += chunk.length;
60 });
61
62 res.on('end', function() {
63 var result = '';
64
65 // Buffer
66 if (opts.isBuffer) {
67 result = Buffer.concat(body, size);
68 } else {
69 body.forEach(function(item) {
70 result += item.toString(opts.encoding);
71 });
72
73 if (opts.json) {
74 result = JSON.parse(result);
75 }
76 }
77
78 callback(null, res, result);
79 });
80 });
81
82 req.on('error', callback);
83
84 if (opts.method !== 'GET' && opts.data) {
85 req.write(opts.data);
86 }
87
88 req.end();
89}
90
91/**
92 * @description
93 * @example
94 * request.post('url', function() {});
95 * request.post({ url: 'url', data: { q1: 'v1' }}, function() {});
96 */
97request.post = function(options, callback) {
98 if (util.isString(options)) {
99 options = {
100 url: options
101 };
102 }
103
104 options.method = 'POST';
105 request(options, callback);
106};
107
108/**
109 * @description
110 * Download remote resurce to local file
111 * @example
112 * request.download({ url: 'path.png' }, function(err, res, body, filepath) {})
113 * request.download({
114 url: 'path.png',
115 rootPath: 'dest/path'
116 }, function(err, res, body, filepath) {
117
118 });
119 */
120request.download = function(options, callback) {
121 var opts = util.extend({
122 rootPath: '',
123 ignore: false
124 }, options);
125
126 request({
127 url: opts.url,
128 isBuffer: true
129 }, function(err, res, body) {
130 if (err) return callback(err);
131 if (res.statusCode !== 200) return callback(err, res, body);
132 var destPath;
133 var pathname = url.parse(options.url).pathname.replace(/^\//, '');
134
135 if (opts.destPath) {
136 if (util.isFunction(opts.destPath)) {
137 destPath = opts.destPath(path.basename(pathname));
138 } else {
139 destPath = opts.destPath;
140 }
141 } else {
142 destPath = path.join(
143 options.rootPath,
144 pathname
145 );
146 }
147
148 if (opts.ignore) {
149 destPath = destPath.toLowerCase();
150 }
151
152 file.writeFile(destPath, body, function(err) {
153 if (err) return callback(err);
154
155 callback(null, res, body, destPath);
156 });
157 });
158};
159
160/**
161 * @description
162 * Http request image, then callback with base64 data.
163 * @example
164 * request.base64(
165 * 'https://www.google.com/images/errors/logo_sm_2_hr.png',
166 * function(err, res, body) {
167 *
168 * }
169 * );
170 */
171request.base64 = function(url, callback) {
172 request({
173 url: url,
174 isBuffer: true
175 }, function (err, res, body) {
176 if (err) return callback(err);
177
178 var data = 'data:' + res.headers['content-type'] + ';base64,' + body.toString('base64');
179
180 callback(err, res, data);
181 });
182};
183
184module.exports = request;
\No newline at end of file