1
\$\begingroup\$

At first I thought this was going to be easy, but the asynchronous Node.js really made things difficult for me. Currently, my tracker only features one coin and the address is hard-coded.

I plan to put this on a server with a far greater selection of coins and other user input. But for that I want the code to be cleaner and faster (if possible).

While making this I often stumbled over the same stones:

  1. How to make Node.js execute code one after another once it's finished.
  2. How to make sure the timestamp gets added to the right object.
  3. How to write out my object to a file only when all data is gathered!

As you can see, I somewhat managed to accomplish step 1 and 2 but I failed at 3.

The structure is as follows:

  1. Go to ubiqscan to get a sum of all transactions made
  2. Iterate over the resulting html and save the data into an object
  3. Get the block's timestamp via the API and add it to the corresponding object
  4. When all is done write the object to a JSONfile

I hope I can get some tips on how to structure or approach this task. Every time I sat down to rewrite this I found myself using the same approach!

App.js

var Promise = require('bluebird')
var request = Promise.promisifyAll(require("request"), {multiArgs: true})
var fs = require('fs')

var blockUrl = 'https://ubiqscan.io/api/v1/getblockarray/'
var txUrl = "https://ubiqscan.io/api/v1/getaddresstxns/0x49cbb931773e446ac665c9b61955b35aab56fa95"
var tempJson = {}

request.getAsync(txUrl).spread(function(response, body){
    console.log('Fetchin tx data: Start')
    var jsonData = JSON.parse(body)
    for (var index = 0; index < jsonData.length; index++) {
        tempJson[index] = {
            val: jsonData[index].value,
            block: jsonData[index].blockNumber,
            time: "placeholder"
        }
    }
    console.log('Fecthing tx data: Complete!')
}).then(function () {
    console.log('Fetchin Block data: Start')
    for (var i in tempJson) {
        var url=blockUrl+tempJson[i].block
        addTimestamp(url,i)
    }
    console.log('Fecthing Block data: Complete!')
 })

 function addTimestamp (url, index,) {
    request(url,function (error, response, html){
        //check for errors
        if(!error && response.statusCode == 200){
             var jsonData = JSON.parse(html.slice(1,-1))
            tempJson[index].time = jsonData.timestamp
            console.log(index)
            fs.writeFileSync('out.json',JSON.stringify(tempJson))
        }
    })
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.