zhanghaoran
文章 文章详情

learn Node.js NO.2: simple apache

阅读:269 分类:Node.js 发布时间:2020-06-09

simple apache

1. Preliminary implementation of Apache functions

适配指定目录下所有文件的访问

var http = require('http');
var fs = require('fs');
// 使用mine模块设置 文件类型
var mime = require('mime');

// 创建服务
var server = http.createServer();
// 指定访问路径
var wwwDir = 'E:\\代码\\learnNode\\2\\resource';

// 监听request请求
server.on('request', function (req, res) {
    var url = req.url;
    var fileName = '/index.html';
    if(url != '/'){
        fileName = url;
    }
    // 读取文件
    fs.readFile(wwwDir + fileName, function (err, data) {
        if(err){
            res.writeHead(404, {'Content-Type': 'text/plain, charset=utf-8'});
            return res.end('404 not fount')
        }
        res.writeHead(200, {'Content-Type': mime.getType(fileName)});
        res.end(data)
    })
});

server.listen(3000, function () {
    console.log('runing')
})

Implementing simple Apache

基本实现apache功能, 缺少:文件和文件夹区分开来

var http = require('http');
var fs = require('fs');
var mime = require('mime');

// 创建服务
var server = http.createServer();
var wwwDir = 'E:\\代码\\learnNode\\2\\resource';

// 监听request请求
server.on('request', function (req, res) {
    var url = req.url;
    var fileName = '/template/index.html';
    if(url != '/'){
        fileName = url;
    }
    console.log(wwwDir + fileName)
    // 读取文件
    fs.readFile(wwwDir + fileName, function (err, data) {
        if(err){
            res.writeHead(404, {'Content-Type': 'text/plain, charset=utf-8'});
            return res.end('404 not fount')
        }
        // 读取文件夹
        fs.readdir(wwwDir, function (err, fileList) {
            if(err){
                res.writeHead(500, {'Content-Type': 'text/plain, charset=utf-8'});
                return res.end('500')
            }
        var content = '';
        fileList.forEach((item)=>{
            content += `
                <tr>
                    <td><a href="${'/'+item}">${item}</a></td>
                </tr>
            `
        });
        data = data.toString();
        data = data.replace('@@', content);
        res.writeHead(200, {'Content-Type': 'text/html; charset: utf-8'});
        res.end(data)
        });

    })
});

server.listen(3000, function () {
    console.log('runing...')
})

Contact me: manbanzhen@qq.com

see you again!