• Node.js学习笔记 01 搭建静态服务器


        希望这篇文章能解决你这样一个问题:“我现在已经了解了一些Node.Js基本概念了,怎么搭一台静态服务器呢?”

        请参考一下博主的前两篇文章:

        完全面向于初学者的Node.js指南

        Node.Js的Module System 以及一些常用 Module

        本文实现的效果(样式就没做了,大家将就下):

       

        列出的代码均测试可用,大家放心。

    What is static server?

         静态服务器,有了它呢,就可以让外部访问到咱们的静态网页。在功能上:它可以给用户发送文件(如:HTML, CSS, Js等)。正如上一篇文章所说:

       Node.js本身并不是像IIS,Apache一样的webserver,它是一个JavaScript 的运行环境。所以,我们需要进行编码才能实现一个真正的京台服务器。

    File stucture

        后台目录建立如下,比较常规。大家可以随意定义目录结构,代码上相应地方改动一下就好。

    app.js

       本文的重点在于接下来的server模块,就不介绍app.js里的代码啦。(把主线代码写在app.js中是个不成文的约定,无需遵守,随意,随意。。。)

    var http = require('http');
    var path = require('path');
    //引入我们自己编写的server模块
    var server = require('./server.js');
    
    http.createServer(function (request, response) {
        //以下的判断用来做简单的路由    
        if (request.url == "/") {
            filePath = path.join(__dirname, '/public/index.html');
        } else {
            filePath = path.join(__dirname, '/public' + request.url);
        }
        server.serveStatic(response, filePath);
    }).listen(/*侦听4000端口*/4000, function () { 
        console.log("Server listening on port 4000");
    });

    MIME

        静态服务器有一个必须实现的功能即为在HTTP报文中指定MIME type. WIKI MIME

        我们会引用一个第三方组件mime,通过npm安装,该组件可以根据文件的extension name映射mime type.

         所以,请在根目录运行一下 npm install mime --save

    server.js

       

    var fs = require('fs');
    //provide the ability to derive a mime type based on the filename extension
    var mime = require('mime');
    
    var cache = {};
    
    //这不是IIS,Apache所以404必须自定义一下,
    function send404(response) {
        response.writeHead(404, { "Content-Type": "text/html" });
        response.write("<h1>ERROR 404 FILE NOT FOUND</h1>");
        response.end();
    }
    
    //向客户端发送文件
    function sendFile(response, filePath, fileContents) {
        response.writeHead(200, { "Content-Type": mime.lookup(filePath) });
        response.end(fileContents);
    }
    
    //这个函数导出,给主模块使用
    function serveStatic(response, absPath) {
        if (cache[absPath]) {
            sendFile(response, absPath, cache[absPath]);
        } else {
            fs.exists(absPath, function (exists) {
                if (exists) {
                    fs.readFile(absPath, function (err, data) {
                        if (err) {
                            send404(response);
                        } else {
                            cache[absPath] = data;
                            sendFile(response, absPath, data);
                        }
                    });
                }
                else {
                    send404(response);
                }
            });
        }
    }
    
    exports.serveStatic = serveStatic;

         解释部分如注释。。。至此,编码部分就完啦。

    How to test

        我们可以在./public 下放一个index.html 内容随意。。。node 跑起来后,只要输入 http://localhost:4000 返回的是它,输入http://localhost:4000/XXX  返回的是404,那么,静态服务器就搭起来了。

    Summary

        这个DEMO过于简单,应该不能满足大家胃口。以后会介绍如何搭一个动态的网站(以Restful service为例)。

     

     
  • 相关阅读:
    A Tour of Go Switch
    A Tour of Go Exercise: Fibonacci closure
    curl的简单使用
    thinkphp自动验证方法的使用
    Forbidden You don't have permission to access / on this server. You don't have permission to access /phpmyadmin/ on this server. 解决办法
    创建、删除文件夹和文件夹里的文件
    图片的copy,从一个目录复制到另一个目录
    如何把内容写入到文件
    读取文件操作
    文件打开操作
  • 原文地址:https://www.cnblogs.com/E-WALKER/p/4619709.html
Copyright © 2020-2023  润新知