How to get stdout data back and forth from child process in Node.js

I’m running a command in node.js using child_process.spawn.
This command has an interactive mode, so that can get the stdin to take input from the console and output results to stdout. I’m using this mode, to send commands to this child via the child.stdin.write( data+'rn' );.

  • I suppose to get the results in the callback child.stdout.on('data'),
    but it seems I’m not getting all data wrote by the command, that I can see in the bash stdout output, but not in the callback.

  • I would like a way to retrieve the data sent with child.stdin.write(
    data+'rn' );
    in order to get the tuple/struct (data,result), since
    the execution is asynchronous.

For convenience, I have added a callback for the child.stdout.on('data') to get results outside that scope.
My code looks like:

    var exec = function(name,command,params,options,callback) {
    var self=this;

    /** default ChildProcess options
     * @see https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options
    */
    var _options = {
        // Prepare child to run independently of its parent process
        //detached: true
    };
    for (var attrname in options) { _options[attrname] = options[attrname]; }

    var created_time= ( new Date() ).toISOString();
    var task = require('child_process').spawn(command, params, _options);
    task.stdout.on('data', function(result) {
        var out=new Buffer(result,'utf-8').toString();
        callback(out);
    });
    task.on('error', function(error) {
        if(self.logger) self.logger.error("exec:%s pid:%d error:n%@",name,task.pid,error);
    });
    task.on('uncaughtException', function (error) {
        if(self.logger) self.logger.error("exec:%s pid:%s uncaughtException:n%@",name,task.pid,error);
    });
    task.stdout.on('end', function(data) {
        if(self.logger) self.logger.debug("exec:%s end.",name);
    });
    task.stderr.on('data', function(data) {
        if(self.logger) self.logger.debug("exec:%s stderr:%s",name,data);
    });
    task.on('close', (code, signal) => {
        if(self.logger) self.logger.warn('task:%s pid:%s terminated due to receipt of signal:%s',name,task.pid,signal);
    });
    task.on('exit', function(code) {
        if(self.logger) self.logger.debug("exec:%s exit.",name);
        if (code != 0) {
            var error=new Error();
            error.description= command + ' ' + params.join(' ');
            error.code=code;
            if(self.logger) self.logger.error("exec:%s pid:%d error:n%@",name,task.pid,error);
        }
        // at exit explicitly kill exited task
        task.kill('SIGINT');
    });
    return task;
}//exec

// load child task
var load = function(model,callback) {
    var m=exec('fasttext','./fasttext', ['predict', model, '-'], {}, callback);
    m.stdout.pipe(process.stdout);
    return m;
}//load

// send data to child task
var send = function(task,data) {
    task.stdin.setEncoding('utf-8');
    task.stdin.write( data );
    task.stdin.write('rn');
}//send

I run the command like

var model=load(modelFile,
function(result) {
    console.log(result);
});
send(model,result);

NOTE.

In this specific case the command was fasttext a command line classification utility by Facebook Inc., that can run in interactive mode when called like ./fasttext predict filePath -.


Source: stackoverflow-javascript

Bash script call to php not returning values

Please can anyone help with this? Trying to auth OpenVPN from a mysql database (wordpress). Have followed this guide https://forums.openvpn.net/viewtopic.php?t=13051
and all scripts etc seems to be working apart from OpenVPN authing at the end.

1: Remote User enters login details in OpenVPN client and tries to connect to server

2: OpenVPN Server saves login details to TMP file, and calls “Helper” script

3: Helper script grabs username & password from TMP file, passes to to “Auth” script to verify & get Result

4: Auth script verifies with MySQL database and gives result to Helper script

5: Helper script tells OpenVPN to allow or deny

If I try log in to OpenVPN, auth fails.
I can monitor the MySQL and see the query being run so its all good until step 4. So you might think Helper isnt giving a result.
But I know that Helper script can output a result because, if I fill in variables manually (and run the Helper script from command line), the Auth script runs the query, and a result is received and outputted to command line!

So in theory, every step is working.
it IS giving an output.
So why on earth when I try to log in with OpenVPN client, it doesnt work?
After all, I can monitor MYSQL and I see the query being run, and I know that step 5 CAN and does output a result. So it should be working!

Any idea what could be wrong please?

Helper script:

TMPFILE=""         # OpenVPN temp file
WPPATH="/var/www/html/rvpn"   # Use full path here, _without_ last slash "/"

# Get basedir for "vpnauth.php"
#BASEDIR=$(/etc/openvpn $0)
VPNUSER="`head -n1 ${TMPFILE} | tail -n1`" # first line
VPNPASS="`head -n2 ${TMPFILE} | tail -n1`" # second line

# Getting results from PHP script
RESULT="`php -f /etc/openvpn/vpnauth.php "${WPPATH}" "${VPNUSER}" "${VPNPASS}"`"
echo "$RESULT"

AUth script:

    $_SERVER['HTTP_HOST'] = 'rvpn_';      // apache and table prefix: "wp_" is the default

ob_start();

// Getting variables arguments
$wordpressdir = $argv[1]; // IGNORE THIS. Not used at present.
$openvpn_user = $argv[2];
$openvpn_pass = $argv[3];


require_once( '/var/www/html/rvpn/wp-load.php' ); // you need to adjust this to your path

// If the query returns username, this user can connect to VPN AFTER PASSWORD CHECK. That's next.
$userresult = $wpdb->get_var( "SELECT user_login FROM rvpn_users WHERE ( (vpn_credit > 0) AND (vpn_enabled = 1) AND (user_login = '$openvpn_user') );" );
// If not empty
if ($userresult) {
   $user = get_user_by('login', "$userresult");
   if ( wp_check_password( "$openvpn_pass", $user->data->user_pass, $user->ID) )
      // Password match
      echo "xOKx";
   else
     // Wrong password
      echo "xWRONGPASSx";

   } else {
   // Woops. User not found
   echo "xWRONGUSERx";
}


Source: stackoverflow-php