V
V
Vladimir2016-01-20 20:03:29
Node.js
Vladimir, 2016-01-20 20:03:29

How to pass the result to a variable?

I want to try to make primitive monitoring, standard NodeJS. Almost everything you need is in os. But you still need to use disks (how much space is occupied / free). I found code examples, but I need to transfer not to the console, but to any variable for further work. Most likely I'm stupid in the basic understanding of JS.

var child_process = require('child_process');

var MyVar;
var MyVar2;

// exec: spawns a shell.
child_process.exec('df -h', function(error, stdout, stderr){
    //console.log(JSON.stringify(stdout, null, 2).split("\\n"));
    MyVar = JSON.stringify(stdout, null, 2).split("\\n");
});

child_process.exec('uptime', function(error, stdout, stderr){
    //console.log(JSON.stringify(stdout, null, 2));
    MyVar2 = JSON.stringify(stdout, null, 2);
});

console.log(MyVar);
console.log(MyVar2);

Variables are undefined, how to pass the result to them?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2016-01-20
@FonVald

No way, you need to use callback or promises.
These are asynchronous requests, console.log is executed before child_process.exec has time to fire.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question