龙空技术网

nodejs 搭建本地 http 服务器

web翎云阁 464

前言:

现在同学们对“phpapache服务器搭建”可能比较关注,咱们都想要知道一些“phpapache服务器搭建”的相关内容。那么小编在网上汇集了一些有关“phpapache服务器搭建””的相关文章,希望各位老铁们能喜欢,姐妹们一起来学习一下吧!

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

nodejs 这玩意儿吧,对做前端的介入后端简直就是一把利器。而且目前,nodejs 也越来越有商用价值。

nodejs 其实是非常底层的,从功能上说,它既是 apache 也是 php。像搭建 http 服务器这种功能,本来是 apache 已经封装好的,但 nodejs 需要我们手动来搭建。其实在实际应用中,我们可以使用现成的框架。但这里,我想手动搭建,也加深一下对 http 服务器的理解。

我们 node 执行下面这个文件,我命名为 http.js,它将创建一个 httpServer 并监听 3000 端口。

http.js

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 + ".");

上面我们还引入了一个 mine.js,这是我自己写的,里面存储的是名值对,用于定义不同后缀的文件所对应的返回方式:

exports.types = {

"css": "text/css",

"gif": "image/gif",

"html": "text/html;charset=utf-8",

"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"

};

fs 模块是用于读取文件的,提供读取文件的方法,其实仔细研究文档会发现,它有同步和异步两种读取方式。

fs.exists 这个方法网上很多文章写作 path.exists,现在推荐写作 fs.exists 这个方法。

否则会报警:

path.exists is now called `fs.exists`.

需要注意的是,不仅浏览器访问 html 文件会形成一次访问,里面链接的 js,css 等外部文件也会分别形成一次 http 访问。

所以,http.createServer 的回调其实是在一次页面访问中执行了多次的。

我们 console.log(realPath) 一下就可以看到:

➜ node https.js

Server runing at port: 3000.

assets/index.html

assets/src/index.css

assets/src/index.js

assets/src/favicon.ico

运行命令行结果

关注 web翎云阁,定时推送,互动精彩多,若你有更好的见解,欢迎留言探讨!

标签: #phpapache服务器搭建 #nodejs启动本地服务器 #node搭建本地服务器运行html #nodejs项目部署在本地服务器