Rob
Rob

Reputation: 2779

node.js scope problems?

I'm working on making a script with node.js for setting up my dzen2 in i3, and haven't really used node for anything like this before.

I need the geometry of the screen to start with, which I can get with something like this:

geometry = getGeo();

function getGeo() {
  var sh = require('child_process').exec("i3-msg -t get_outputs",
    function(error, stdout, stderr) {
      var out = JSON.parse(stdout);
      return out[0].rect; //this is the geometry, {"x":0, "y":0, "width":1280, "height":768}
  });
};

console.log(geometry);

console.log is logging undefined.

I'm not sure what the proper way to do this is, my brain is tired.

Upvotes: 1

Views: 191

Answers (2)

Robert Wilson
Robert Wilson

Reputation: 669

You can't return from the callback function since is async. Rather write another function and pass the callback object to it.

function getGeo() {
var sh = require('child_process').exec("i3-msg -t get_outputs",
    function(error, stdout, stderr) {
      var out = JSON.parse(stdout);
      getRect(return out[0].rect);
    });
};

function getRect(rect) {
    // Utilize rect here...
}

Upvotes: 3

Ned Batchelder
Ned Batchelder

Reputation: 375484

You never return a value from getGeo(), you're returning a function from the anonymous function within it. But because of the async nature of the .exec() call, you can't return the value. You can put the console.log into the callback function, but that may not be where you want to use it in your real program.

Upvotes: 0

Related Questions