request.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const http = require('http')
  2. const https = require('https')
  3. function doRequest (options) {
  4. const { ssl, encoding, requestOptions } = options
  5. return new Promise((resolve, reject) => {
  6. let responseText = ''
  7. const responseBinary = []
  8. const httpRequest = ssl ? https.request : http.request
  9. const req = httpRequest(requestOptions, function (response) {
  10. if (encoding !== 'binary') {
  11. response.setEncoding(encoding)
  12. }
  13. response.on('data', function (chunk) {
  14. if (encoding === 'binary') {
  15. responseBinary.push(chunk)
  16. } else {
  17. responseText += chunk
  18. }
  19. })
  20. response.on('end', function () {
  21. const result = {
  22. error: null,
  23. data: { statusCode: response.statusCode, headers: response.headers }
  24. }
  25. if (encoding === 'binary') {
  26. result.data['binary'] = Buffer.concat(responseBinary)
  27. } else {
  28. result.data['text'] = responseText
  29. }
  30. resolve(result)
  31. })
  32. response.on('error', function (error) {
  33. reject(error)
  34. })
  35. }).on('error', function (error) {
  36. reject(error)
  37. })
  38. req.end()
  39. })
  40. }
  41. (async () => {
  42. try {
  43. const args = process.argv.slice(2)
  44. const options = {}
  45. for (let j = 0; j < args.length; j++) {
  46. const arg = args[j]
  47. if (arg.startsWith('--ssl=')) {
  48. options.ssl = arg.slice('--ssl='.length) === 'true'
  49. } else if (arg.startsWith('--encoding=')) {
  50. options.encoding = arg.slice('--encoding='.length)
  51. } else if (arg.startsWith('--request-options=')) {
  52. options.requestOptions = JSON.parse(arg.slice('--request-options='.length))
  53. }
  54. }
  55. const result = await doRequest(options)
  56. console.log(JSON.stringify(result))
  57. } catch (e) {
  58. console.log(JSON.stringify({ 'error': e }))
  59. }
  60. })()