ice7

Node Get Request

Jun 13th, 2017
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var http = require('http');
  2. var express = require('express');
  3. var numeral = require('numeral');
  4. var moment = require('moment');
  5. var open = require('open')
  6.  
  7. var app = express();
  8.  
  9. var port = 3000;
  10.  
  11. app.listen(port, function(err){
  12.     open('http://localhost:' + port);
  13. });
  14.  
  15. app.get('/', function(req, rep){
  16.     rep.write('Everything is good');
  17.     rep.end();
  18. });
  19.  
  20. app.get('/btc', function(req, resp){
  21.     resp.write('Todays price...')
  22.     btc(function(data){
  23.         resp.write('Price: ' + data.price + '\r');
  24.         resp.write('Date: ' + data.timeStamp);
  25.         resp.end();
  26.     });
  27. });
  28.  
  29. function btc(callback){
  30.  
  31.     var options = {
  32.         hostname: 'winkdex.com',
  33.         path: '/api/v0/price',
  34.         method: 'GET',
  35.         port: 80,
  36.         headers: {}
  37.     };
  38.  
  39.     http.request(options, function(resp){
  40.  
  41.         var data = '';
  42.         var btc = {};
  43.  
  44.         resp.on('data', function(chunk){
  45.             data += chunk
  46.         });
  47.  
  48.         resp.on('end', function(){
  49.             var result = JSON.parse(data);
  50.             btc.price = numeral(result.price / 100).format('$0.00');
  51.             btc.timeStamp = moment(result.timestamp).format('DD/MM/YYYY');
  52.  
  53.             callback(btc);
  54.         });
  55.  
  56.     }).on('error', function(err){
  57.         console.log(err);
  58.     }).end();
  59. }
Advertisement
Add Comment
Please, Sign In to add comment