0

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.

  • If, in fact, `let freeSpace = this.obtainMemory(ip);` returns the value you need for a single raspberry pi, you could keep track of the device with the most memory available and only update it, if the current device has more memory available. You need to consider async behaviour of course. – Andreas Mar 20 '22 at 20:40

1 Answers1

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 }
}