gpt4 book ai didi

php - 允许 Node.js Web 服务器处理 PHP

转载 作者:太空宇宙 更新时间:2023-11-03 22:32:09 25 4
gpt4 key购买 nike

我有一个使用 Node.js 创建的支持多种文件类型的 Web 服务器,我想将 PHP 集成到 Node.js 中,因此如果用户希望使用 PHP 脚本,我的 Web 服务器会知道如何来处理它。

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

感谢任何帮助,谢谢

最佳答案

对于以下代码,您需要在主机上安装 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!");

关于php - 允许 Node.js Web 服务器处理 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35131751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com