How to run PHP Script in Node.js?

I am trying to run php code in Node.js. But while typing localhost:4000 in the browser the whole code of index.php is getting displayed in the browser.

Node.js code

var http = require('http'),
fs = require('fs'),
var app = http.createServer(function (request, response) {
fs.readFile("index.php", 'utf-8', function (error, data) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.write(data);
    response.end();
}); }).listen(4000);

PHP Code:

<?php

$handle = fopen("data.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {

         echo $line;
         echo '<br>';
    }
} else {
    // error opening the file.
} 
 fclose($handle);
?>

So , please let me know , how can i run PHP code through node.js , suggest me some solution.

Node.js cannot run PHP out of the box. It is not a PHP server, and cannot parse PHP code. You might be able to use a JavaScript PHP shim, but these will likely not have reliable performance.

One such option is php.js, which is a JavaScript PHP VM, but even still, I do not recommend this.

My wholehearted recommendation is that you convert your code to Node.js if you're going to use Node.js at all. Your code is relatively trivial to convert as well. See Node.js' built in fs API. In particular, the fs.readFile() function which you are already using to read the PHP file.

If you need to convert each new line into an HTML page break, that's also relatively trivial. First, you'll want to coerce the data to a string using the toString() method. You can also use Regex matching, or use split() and join() to convert newlines into </br>. For this example, I'll use the split()/join() method.

E.g.

fs.readFile('filename.txt', 'utf-8', function(err, data) {
    var str = data.toString();
    str = str.split(/\r\n|\r|\n/g).join('</br>');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write(str);
    res.end();
});