CentOS 7 用nodejs搭建web服务器

来源:互联网 发布:琼州海峡隧道 知乎 编辑:程序博客网 时间:2024/06/04 17:43

0.linux部署web服务器可用tomcat但相对复杂,可考虑简单的nodejs方法
1.linux系统首先安装好nodejs. 通过node -v查看一下版本,我的版本是v0.10.35
2.开启服务器端口,否则有可能客户端访问不了(以8080端口例)
#firewall-cmd –zone=public –add-port=8080/tcp –permanent
3.重启防火墙 #firewall-cmd –reload
4. 编写两个js代码文件,先写一个http.js

var PORT = 8080;//设置通讯端口var http = require('http');var url=require('url');var fs=require('fs');var mine=require('./mediaType').types;//var path=require('path');var server = http.createServer(function (request, response) {    var pathname = url.parse(request.url).pathname;    var realPath = path.join("root", pathname);    //这里设置自己的文件根目录名称;    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 + ".");

mediaType.js (用于引用对应media文件,其实是数组)

exports.types = {  "css": "text/css",  "gif": "image/gif",  "html": "text/html",  "ico": "image/x-icon",  "jpeg": "image/jpeg",  "jpg": "image/jpeg",  "js": "text/javascript",  "json": "application/json",  "pdf": "application/pdf",  "png": "image/png",  "svg": "image/svg+xml",  "swf": "application/x-shockwave-flash",  "tiff": "image/tiff",  "txt": "text/plain",  "wav": "audio/x-wav",  "wma": "audio/x-ms-wma",  "wmv": "video/x-ms-wmv",  "xml": "text/xml"};

这里写图片描述

文件目录架构.
只需要将http.js和mediaType.js放在同一目录,新建一个root文件夹,然后放用户需要访问的网页进去,启动服务器,打开项目所在目录运行指令node http.js 即可访问类似如下地址:
http://localhost:8080/index.html

可根据自己需求修改端口参数,index.html先放到root文件夹中.

Complete !

原创粉丝点击