简体   繁体   中英

Node.js execSync returning undefined but console.log works

I've seen a similar question once, but I can't for the life of me figure out why this isn't working. I have a pretty simple program below that should wrap the exec function and return the result. However all it returns is undefined. Here's the function:

var exec = require('child_process').execSync;

quickexec = function(command) {
    exec(command, function(error, stdout, stderr) {
        if(error) {
            return error;
        } else {
            return stdout;
        }
    });
};

I call it like this console.log(quickexec('echo -n $USER')); and I get undefined everytime. However if I change the return in my function to a console.log it works. I thought that it was an async problem which is why I started using execSync , but it didn't change anything.

quickexec() does not actually return anything. The return inside it are in the async callback which happens long after quickexec() has already returned. You can't synchronously return an asynchronous result. This is a common issue when learning how to do proper asynchronous programming in node.js.

If you need a synchronous result, you can use execsync() , but usually the best design is to use the asynchronous result in the callback.

var quickexec = function(command, callback) {
    exec(command, function(error, stdout, stderr) {
        if(error) {
            callback(error);
        } else {
            callback(null, stdout);
        }
    });
};

quickexec('echo -n $USER', function(err, result) {
    // use the result here in the callback
    if (err) {
        console.log(err);
    } else {
        console.log(result);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM