Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

75
Visualizações
Find the max result of various HTPP request

this is my first stackoverflow post. In this NodeJS app, the objective is to get the max value of memory avaible from a IP's pool. I know that I can use the function obtainMemory with a callback but idk how to use in this scenario.

decide(){
for(var i=0;i < raspberrys.length;i++ ){
            let ip =  raspberrys[i];
            let freeSpace =  this.obtainMemory(ip);
            console.log(freeSpace);
        }
},obtainMemory(ip){
       https.get('http://'+ip+':3030/memory', (response)=>{
            let data='';
            response.on('data', (chunk) =>{
                data+=chunk;
            });

            response.on('end',()=>{
               let obj = JSON.parse(data);
               console.log(obj.free );
               return obj.free;
            })

        }).on('error',(error)=>{
            console.log(error);
        });
            
    }

For example if i have 2 raspberrys with 2GB and 1MB, I have to return the IP of the first raspberry. Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Just to make it easier I would transform the get into a promise. You can do that installing some library like got, node-fetch or axios. If you have access to node 17.5 you can use the, now native, fetch you can see how here. I made a promisified version of get too:

const get = (url) => {
  return new Promise((resolve, reject) => {
    let data = ""
    const req = https.get(url, (res) => {
      res.on("data", (chunk) => (data += chunk))
      res.on("error", (err) => reject(err))
      res.on("end", () => {
        data = JSON.parse(data)
        return resolve(data)
      })
    })
    req.on("error", reject)
    req.end()
  })
}

You can find a more complete version here.

using it your code:

async function decide() {
  // get all raspberrys free memory
  const freeMemories = await Promise.all(raspberrys.map(obtainMemory))

  // find which one has the biggest memory
  const { ip } = freeMemories.reduce(
    (prev, curr) => {
      if (prev.memory < curr.memory) prev = curr

      return prev
    },
    { memory: 0 }
  )

  console.log(ip)
}

async function obtainMemory(ip) {
  const ipAddress = `http://${ip}:3030/memory`
  const { free } = await get(ipAddress) // using the get function that I defined

  return { ip, free }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda