简体   繁体   中英

Running php code inside a node.js socket server script

I am running a normal TCP socket in javascript and uses node to execute. Before I send a response back to the client, I want to validate the data with some some php (mysql) code. How can I execute this code inside this javascript file? All similar questions in STACKOVERFLOW asks about this code in HTML. (which is okay and I understand that part), But this is a normal javascript file (executed in node). The javascript code is below and I've marked the validation function call.

var net = require('net');

var HOST = '192.168.0.6';
var PORT = 8765;

net.createServer(function(sock) {

    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

    sock.on('data', function(data) {
        var output;
        var validScan;

        //This is the function call to a php file
        **validScan = validateScanTag(data);**

        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        sock.write(validScan);

    });

    // Closing this instance of socket
    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

The validateScanTag executes a line lke :

$.post('getperiod.php', {hours:hrs, minutes:mins, seconds:secs, ddd:day},

But this dont work. How can I call this 'geteriod.php' file from a javascript file?

I'm pretty sure the problem itself is well worth rethinking (for example, port your mysql code from php to node) but here is my solution:

var net = require('net');
var PORT = 8765;
var Lazy=require('lazy');
var spawn = require('child_process').spawn;

// php code runs as a server in external process

var validator = spawn('php', ['validator.php']);

net.createServer(function(sock) {

    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

    // on 'data' handler is not enough to read input line by line
    // you need to buffer data, use some kind of state machine or one of available stream parsers. I use lazy here: npm install lazy

    // write each line to php validation code
    new Lazy(sock).lines.forEach(function(line) {
        console.log('DATA ' + sock.remoteAddress + ': ' + line.toString());
        validator.stdin.write(line);
        validator.stdin.write('\n');
    });

    // read validation result line by line from validator process
    new Lazy(validator.stdout).lines.forEach(function(line) {
        console.log('Validation result:' + line.toString()) // line is Buffer object here, hence toString
    });

    validator.stdout.pipe(process.stdout);

    // Closing this instance of socket
    sock.on('close', function() {
        console.log('CLOSED');
    });

}).listen(PORT);

validator.php should read from stdin and write to stdout

<?

function validatescanTag($l) {
    // put your validation code here
    return $l . '!!!!';
}

$stdin = fopen('php://stdin', 'r');

do {
  $line = fgets($stdin);
  print validateScanTag($line);
} while(1);

?>

Another option is to use fastcgi protocol to communicate node <-> php or dnode rpc . Or just use http and run php from nginx/apache (or even node-php )

An approach to give a more generic answer for clarification and "getting you on the boots":

As far as I understand you're trying to run your php script using a http post request invoked by the node.js server.

You probably first have to become aware of the fact that running server-side JavaScript normally has different motivation and possibilities as well as impacts on your architecture than running JS inside a browser - at least in a classical "jQuery sense".

As stated in your comment you expect jQuery to work seamlessly within server-side node.js. That doesn't work as the comment-posted ReferenceError: $ is not defined shows you. There is no server-side jQuery available in your node.js stack working out-of-the-box (possibilities of using jQuery server-side should be discussed separately and is another subject).

Nevertheless you're obviously looking for a way to re-use your PHP script which already handles your mysql data connection and handling by utilizing it server-side . Doing this using http there are possibilites like shown in this stackoverflow post or in the http.request section of the node.js documentation . If your php script resides on the same server (or better runtime environment) as your node.js is running you may also directly execute the php script it by spawning it as a child process with the php standalone (command line) utility.

Last but not least: Yes, there are some ways (npm modules, ORM layers) for connecting mysql directly with your node.js app. But that's another complex subject and is discussed at other places.

I hope that helped in a way to avoid mixing up things that shouldn't be mixed up.

有一个PHP扩展在PHP中嵌入了Chrome的V8引擎

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