C
C
cat_crash2018-03-13 20:39:18
Node.js
cat_crash, 2018-03-13 20:39:18

NodeJS: How to write a correct function returning a Json object?

I want to transfer metrics from a piece of iron on which NodeJS is spinning. Metrics are collected by different libraries under NodeJS
The task is to throw a JSON object containing data every 5 seconds
How to solve the problem in a classical synchronous language is not a mystery to me. But with a node, this approach does not work.
An example of which I "win"
...

//Делать замер каждые 3 секунды
setInterval(function(){
    var data = getData();
}, 3000);

function getData(){
sensor.read(11, 6, function(err, temperature, humidity) {
        if (!err) {
            h=humidity.toFixed(1);
            t=temperature.toFixed(1);
        }
    });

    os.cpuUsage(function(v){
        cpu=v*100;
    });

    os.cpuFree(function(v){
        cpu2=v*100;
    });

    totalmem=os.totalmem();
    freemem=os.freemem();

    var ret={
        'freemem':freemem,
        'totalmem':totalmem,
        'temp':t,
        'hum':h,
        'cpu':cpu,
        'cpu2':cpu2,
    };
return ret;
}

...
further sending data data to setInterval

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Abcdefgk, 2018-03-13
@Abcdefgk

Maybe like this (but it's not accurate):

setInterval(function(){
  getData().then( data => {
    console.log(data);
  });
}, 3000);

async function getData() {
  var [h, t] = await new Promise( resolve => {
    sensor.read(11, 6, function(err, temperature, humidity) {
            resolve( [humidity.toFixed(1), temperature.toFixed(1)] );
    });
  });

  var cpu = await new Promise( resolve => {
    os.cpuUsage(function(v){
        resolve(v*100);
    });
  });

  var cpu2 = await new Promise( resolve => {
    os.cpuFree(function(v){
        resolve(v*100);
    });
  });

  var totalmem = os.totalmem();
  var freemem = os.freemem();

  var ret = {
    freemem: freemem,
    totalmem: totalmem,
    temp: t,
    hum: h,
    cpu: cpu,
    cpu2: cpu2,
  };
  return JSON.stringify(ret);
}

E
eternalSt, 2018-03-14
@eternalSt

Good day!
You have a number of errors in your code that occur precisely because of not understanding how asynchrony works in Node JS. Watch this NodeJS course by Ilya Kantor (see 20-21 videos) where everything is described in detail about asynchrony.
And you can write working code yourself.
PS After you understand everything and everything about callback . Explore generators , promises and async functions .
PPS If you can't figure it out at all. Then say, we will solve the problem =) In the meantime, try to figure it out yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question