Vitor
Vitor

Reputation: 191

Variable not get anything

I am running a code in nodejs that does console.log from variable without problems, but then the variable a does not contain anything:

var a='';
var util   = require('util'),
    exec  = require('child_process').exec,
    child;

child = exec('ifconfig eth0',
    function (error, stdout, stderr) {
         a=stdout.toString();
         console.log(a);
})

Is there anything wrong that makes it not store the stdout message to variable a?

Upvotes: 0

Views: 379

Answers (2)

Vitor
Vitor

Reputation: 191

tanks for reply I found the problem, Its true that I need to have in consideration stderr but the code is only a small demo I solve the problem declaring variable a as an array var a= []

var a= []

var util   = require('util'),
    exec  = require('child_process').exec,
    child;

child = exec('ifconfig eth0',
    function (error, stdout, stderr) {
         a[0]=stdout.toString();

})

Now variable a contains the string from stdout for future usage

Consider this post SOLVED

Regards

Upvotes: 0

Rohan Singh
Rohan Singh

Reputation: 21455

If there is an error executing ifconfig eth0, then there will be no value in stdout. For example, my machine doesn't actually have an interface named eth0, so nothing is returned in stdout.

Try executing ifconfig eth0 manually to see what happens. You could also modify your code like this:

var a='',b='';
var util   = require('util'),
    exec  = require('child_process').exec,
    child;

child = exec('ifconfig eth0',
    function (error, stdout, stderr) {
         a=stdout.toString();
         b=stderr.toString();
         console.log(a);
         console.log(b);
})

Alternatively, perhaps you mean that the console.log does actually log the output to the console, but the variable a then appears to be empty?

If this is the case, make sure you are accessing a at the right time. Simply trying to read a after the last line of the code you posted would not work, since the callback that sets a=stdout.toString() would not have run yet.

Upvotes: 1

Related Questions