Skip to content

Instantly share code, notes, and snippets.

@y-a-v-a
Last active November 11, 2020 14:58
Show Gist options
  • Save y-a-v-a/da75a0f5da80d48c9dbd2345dd8e8821 to your computer and use it in GitHub Desktop.
Save y-a-v-a/da75a0f5da80d48c9dbd2345dd8e8821 to your computer and use it in GitHub Desktop.
Nodejs php web server
//Lets require/import the HTTP module
var http = require('http');
var fs = require('fs');
var PORT=8080;
var spawn = require('child_process').spawn;
//We need a function which handles requests and send response
function handleRequest(request, response) {
console.log('Requested file: ' + request.url);
var file = request.url
if (file === '/') {
file = '/index.php';
}
if (file === '/favicon.ico') {
response.end('');
}
if (file.substr(file.length - 4, 4) === '.php') {
var php = spawn('php', ['.' + file]);
php.stdout.on('data', function(data) {
response.write(data);
});
php.on('close', function() {
response.end();
});
} else {
fs.readFile('.' + file, function(error, file) {
response.end(file);
});
}
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});
@y-a-v-a
Copy link
Author

y-a-v-a commented Jun 10, 2016

An easy alternative could be to let PHP start a server on a port from the command line:
$ php -S localhost:8080

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment