0

I'm trying to get the value of a variable outside the function, but it always return undefined

I tried with callback but when I run the script it return callback is not a function

const exec = require('child_process').exec;

let data;
const command = "df -g | awk '$4+0 >= 80 { print $4, $7 }' | sort -n";

let exe = exec("ssh user@sistemName " + command, function (error, data, stderr ) {

});

console.log(data);

I expect value of file systems that are > than 80%

Jeroen Heier
  • 3,520
  • 15
  • 31
  • 32
  • how do you get the content of a box, before you have the box/ before it is delivered? your problem is not the scope of variables, your problem is time! – Thomas Jun 26 '19 at 16:47

1 Answers1

0

As long as you did not assign the value for data variable, by default it has "undefined".

  1. You can not do like this, since javascript is a event-loop/callback-oriented. You don't know when the exec function will be finished and callback will be fired to fill the data variable. It will be later then you're trying to get it on line below. Moreover your data actually "parameter".

  2. Why do you need to reach this variable outside of the callback? If you need to use this variable in some "other part" of functionality, you can do like this

    const exec = require('child_process').exec;
    function someOtherFunction(data) {
        console.log(data)
    }
    let data;
    const command = "df -g | awk '$4+0 >= 80 { print $4, $7 }' | sort -n";

    let exe = exec("ssh user@sistemName " + command, function (error, data, stderr ) {
      someOtherFunction(data);
    });

Viktor
  • 188
  • 7
  • Hi Viktor, I need to get the variable outside the function because I am calling this script from another one using export, but as the variable is inside a function, in the other script when I call the variable it return undefined – Rodrigo Menchaca Jun 26 '19 at 17:02
  • I suppose you have to export the functionality, not the data variable, and use this functionality inside another script passing callback/or via promises. e.g function f() { return new Promise((resolve, reject) => { const command = "df -g | awk '$4+0 >= 80 { print $4, $7 }' | sort -n"; let exe = exec("ssh user@sistemName " + command, function (error, data, stderr ) { resolve(data); }); }); } module.exports = f; Then in another script, import "f" in another script, and use f().then(res => console.log(res)); – Viktor Jun 26 '19 at 17:13