nodejs搭建本地http服务器教程-创新互联
由于不做php相关的东西,懒得装apache,干脆利用nodejs搭建一个本地的服务器用于测试。

nodejs这玩意儿吧,对做前端的介入后端简直就是一把利器。而且目前,nodejs也越来越有商用价值。
nodejs其实是非常底层的,从功能上说,它既是apache也是php。像搭建http服务器这种功能,本来是apache已经封装好的,但nodejs需要我们手动来搭建。其实在实际应用中,我们可以使用现成的框架。但这里,我想手动搭建,也加深一下对http服务器的理解。
我们node执行下面这个文件,我命名为http.js,它将创建一个httpServer并监听3000端口。
var PORT = 3000;
var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./mine').types;
var path=require('path');
var server = http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;
var realPath = path.join("assets", pathname);
//console.log(realPath);
var ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
fs.exists(realPath, function (exists) {
if (!exists) {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.write("This request URL " + pathname + " was not found on this server.");
response.end();
} else {
fs.readFile(realPath, "binary", function (err, file) {
if (err) {
response.writeHead(500, {
'Content-Type': 'text/plain'
});
response.end(err);
} else {
var contentType = mine[ext] || "text/plain";
response.writeHead(200, {
'Content-Type': contentType
});
response.write(file, "binary");
response.end();
}
});
}
});
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");
另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
分享文章:nodejs搭建本地http服务器教程-创新互联
标题网址:http://www.jxjierui.cn/article/dgcocs.html


咨询
建站咨询
