Skip to content
Advertisement

Extract the price only from api using node-fetch array

I am sorry for a basic question, I have been trying to extract only the price using node-fetch from API

const fetch = require('node-fetch');

fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
    .then(res => res.text())
    .then(text => console.log(text))
    
    let AvgPrice = text.map(text => text.price);

The error I am receiving is

internal/modules/cjs/loader.js:968
  throw err;
  ^

Please, any suggestion is greatly appreciated

Advertisement

Answer

There are several things that you need to check out

  1. Errors reagarding cjs/loader.js have little or nothing to do with your code per se but rather the setup, for example how you run the code, naming of the file, etc,

internal/modules/cjs/loader.js:582 throw err https://github.com/nodejs/help/issues/1846

  1. This code will return Reference error: text is not defined.

The reason is that you never define the variable text and then you try to call map function on it.

Also fetch is a async function and nodejs is single threaded non-blocking. So what happens is that you send a http request (fetch) to the website, that takes times, but meanwhile your coding is still running, so continues to the next line in your code.

Lets add some console logs

const fetch = require('node-fetch');

console.log('1. lets start')
fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
    .then(res => res.text())
    .then(text => {
      console.log('2. I got my text', text)

    })
console.log('3. Done')

You might think that this will log out

  1. lets start
  2. I got my text {“mins”:5,”price”:”0.4998″}
  3. Done

Nopes, it will log out

  1. Lets start
  2. Done
  3. I got my text {“mins”:5,”price”:”0.4998″}

Because you fetched the data, then your program continued, it looged out 3. Done and THEN when it got the data from api.binance it logged out 2. I got my text (notice the keyword then, it happens later)

  1. map is a function for arrays. What the api returns is an object. So when you fix your async code, you will get TypeError text.map is not a function

Since it returns an object you can access it’s property right away text.price

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement