简体   繁体   中英

Meteor._wrapAsync and node child processes

I try to get results from child_process commands in Meteor environment. It seems that there is something special in child_process, which I don't understand. Here is the code I used for testing

Meteor.startup(function () {
    exec = Npm.require('child_process').exec;
});

function bind_environment_callback(error) {
    console.log('Error binding environment for a callback', error.stack);
}

function get_git_commit_hash(cb) {
    exec( 
        'git rev-parse HEAD',
        Meteor.bindEnvironment(
            function(error, stdout, stderr) {
                if (error) {
                    cb('Error retrieving commit hash', null);
                } else {
                    console.log("Inside get_git_commit_hash:" + stdout.slice(0,stdout-1).toString());
                    cb(null, stdout.slice(0,stdout-1).toString());
                }
            },
            bind_environment_callback
        )
    );
}

function dummy(cb){
    setTimeout(function(){
        cb(null, 'Dummy result');
    },
    100);
}

Meteor.methods({
    test: function() {
        var get_git_commit_hash_sync = Meteor._wrapAsync(get_git_commit_hash);
        var result= get_git_commit_hash_sync();
        console.log('Call 1:' + result);

        var dummy_sync = Meteor._wrapAsync(dummy);
        result= dummy_sync();
        console.log('Call 2:' + result);
    }
});

When I run Meteor.call('test') in the browser, I see the following output in the console:

Inside get_git_commit_hash:d53ffc7f5db26c6e2b40bfcce7a1e2e0d6610ece
Call 1:
Call 2:Dummy result

Can anybody help me understanding why I don't get the result in the first call?

I'm not sure if this will work but give it a try:

runCmd = Meteor.wrapAsync(exec)

var result = runCmd("git rev-parse HEAD");

console.log(result);

Then you can process result after. Also beware you have done stdout-1 , which should always return NaN for the command you are running, and not a number.

Update

Meteor._wrapAsync is now Meteor.wrapAsync

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