允许Node.js webserver处理PHP

我有一个使用支持多种文件types的Node.js创build的Web服务器,我想将PHP集成到Node.js中,所以如果用户希望使用PHP脚本,我的Web服务器将知道如何处理它。

我已经读了关于Nginx,php.js和其他几个指南,想知道是否有人有其他更简单的方法,或者有更新的节点框架为此创build?

任何帮助表示赞赏,谢谢

对于下面的代码,你将需要在主机上安装php并添加到$ PATH。 不要试图重新发明轮子,你需要的一切已经为你做了,你所要做的就是连接点。

var http = require("http"), fs = require("fs"), path = require("path"), url = require("url"), wildcard = require("wildcard"), runner = require("child_process"); function sendError(errCode, errString, response) { response.writeHead(errCode, {"Content-Type": "text/plain"}); response.write(errString + "\n"); response.end(); return false; } http.createServer(function(request, response) { var uri = url.parse(request.url).pathname , filename = path.join(process.cwd(), uri); var contentTypesByExtension = { '.html': "text/html", '.css': "text/css", '.js': "text/javascript", '.avi' : "video/x-msvideo", '.exe' : "application/octet-stream", '.gif' : "image/gif", '.htm' : "text/html", '.ico' : "image/x-icon", '.png' : "image/png", '.jpeg' : "image/jpeg", '.jpg' : "image/jpeg", '.mp3' : "audio/mpeg", '.mpeg' : "video/mpeg", '.pdf' : "application/pdf", '.sh' : "application/x-sh", '.snd' : "audio/basic", '.src' : "application/x-wais-source", '.svg' : "image/svg+xml", '.tar' : "application/x-tar", '.tgz' : "application/x-compressed", '.txt' : "text/plain", '.zip' : "application/zip", '.woff' : "application/font-woff", '.woff2' : "application/font-woff2" }; var param = url.parse(request.url).query; fs.exists(filename, function(exists) { if(!exists) { response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\n"); response.end(); return; } if (fs.statSync(filename).isDirectory()) filename += '/index.html'; fs.readFile(filename, "binary", function(err, file) { if(err) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(err + "\n"); response.end(); return; } var headers = {}; var contentType = contentTypesByExtension[path.extname(filename)]; if (contentType) { headers["Content-Type"] = contentType; response.writeHead(200 + " " + headers); response.write(file, "binary"); response.end(); } else if(filename.indexOf(".php") >= 0) { var tmp = filename.replace(/ /g, '\\ '); runner.exec("php " + tmp + " " + param, function(err, phpResponse, stderr) { if(err) console.log(err); /* log error */ response.writeHead(200, {"Content-Type": "text/plain"}); response.write( phpResponse ); response.end(); }); } }); }); }).listen(1000); console.log("Server started on http://localhost:1000/"); console.log("Server supports HTML, CSS, JS and PHP!");