美文网首页
匹配任意文件和处理不存在的文件

匹配任意文件和处理不存在的文件

作者: kzc爱吃梨 | 来源:发表于2022-02-09 16:27 被阅读0次
import * as http from "http";
import {IncomingMessage, ServerResponse} from "http";
import * as p from 'path';
import * as fs from "fs";
import * as url from "url";

const server = http.createServer();
const publicDir = p.resolve(__dirname, 'public');  // __dirname表示当前文件所在目录

server.on('request', (request: IncomingMessage, response: ServerResponse) => {
    const {method, url: path, headers} = request
    const {pathname, search} = url.parse(path)
    // response.setHeader('Content-Type', 'text/html; charset=utf-8')
    let fileName = pathname.substr(1)  //  /index.html => index.html
    if (fileName === '') {
        fileName = 'index.html'
    }
    fs.readFile(p.resolve(publicDir, fileName), (error, data) => {
        if (error) {
            if (error.errno === -4058) {
                response.statusCode = 404
                fs.readFile(p.resolve(publicDir, '404.html'), (error,data)=> {
                    response.end(data)
                })
            } else if (error.errno === -4068) {
                response.statusCode = 403
                response.end('无权查看目录内容')
            } else {
                response.statusCode = 500;
                response.end('服务器繁忙,请稍后再试')
            }
        } else {
            response.end(data)
        }
    })
})

server.listen(8888)

相关文章

  • 匹配任意文件和处理不存在的文件

  • 通配符及管道命令

    一.常用通配符 globbing:文件名通配(整体文件名匹配,而非部分)匹配模式:元字符 *:匹配任意长度的任意字...

  • 2018-03-25glob及IO重定向(01)

    文件名通配 匹配模式:元字符 *:匹配任意长度的任意字节 ?:匹配任意单个字符 【】:匹配指定范围内...

  • Linux 文件搜索

    find 匹配任意内容? 匹配任意一个字符[] 匹配任意一个中括号内的字符不区分大小写查找文件 安装文件所有者查找...

  • 【Linux入门第9天】glob及IO重定向

    bash基础特性 globbing:文件名通配 匹配模式:元字符 *:匹配任意长度的任意字符 ...

  • glob

    glob匹配规则 glob主要为筛选文件 * 匹配任意 0 或多个任意字符 ? 匹配任意一个字符 [...] 若字...

  • 二、数据的存储与检索

    1、文件处理流程 文件处理流程:写入文件流程: 打开文件,文件不存在就创建; 将数据写入文件; 关闭文件。读文件流...

  • 2017-12-25

    linux 中文件通配符号 * 匹配任意字符 ?匹配任意单个字符 【】制定范围内的单个字符 【a-zA-Z】 [^...

  • 英文文档翻译--Kotlin(一、基础语法)

    基础语法 定义包包说明需要定义在源文件的最顶部 文件路径与包不需要完全匹配:源文件可以放在文件系统的任意位置 定义...

  • ant风格的路径

    ant风格资源地址支持3种匹配符: 1. ?:匹配文件名中的一个字符 2. *:匹配文件名中的任意字符 3. **...

网友评论

      本文标题:匹配任意文件和处理不存在的文件

      本文链接:https://www.haomeiwen.com/subject/yeinhrtx.html