手机版
你好,游客 登录 注册
背景:
阅读新闻

Nodejs搭建本地http服务器

[日期:2014-06-14] 来源:Linux社区  作者:shawn-xie [字体: ]

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

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

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

Node.Js入门[PDF+相关代码] http://www.linuxidc.com/Linux/2013-06/85462.htm

Node.js入门开发指南中文版 http://www.linuxidc.com/Linux/2012-11/73363.htm

Node.js安装与配置 http://www.linuxidc.com/Linux/2013-05/84836.htm

Ubuntu 编译安装Node.js http://www.linuxidc.com/Linux/2013-10/91321.htm

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

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

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

fs模块是用于读取文件的,提供读取文件的方法,其实仔细研究文档会发现,它有同步和异步两种读取方式。fs.exists这个方法网上很多文章写作path.exists,,现在推荐写作fs.exists这个方法。否则会报警:

需要注意的是,不仅浏览器访问html文件会形成一次访问,里面链接的js,css等外部文件也会分别形成一次http访问。所以,http.createServer的回调其实是在一次页面访问中执行了多次的。我们console.log(realPath)一下就可以看到:

这里并没有加入默认访问index.html的功能,所以访问地址要写全http://127.0.0.1:3000/index.html

Node.js 的详细介绍请点这里
Node.js 的下载地址请点这里

本文永久更新链接地址http://www.linuxidc.com/Linux/2014-06/103143.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款