A directory structure

The second index. Ts
//index.ts
import * as http from 'http';
import {IncomingMessage, ServerResponse} from 'http';
import * as fs from 'fs';
import * as p from 'path';
import * as url from 'url';

const server = http.createServer();
const publicDir=p.resolve(__dirname,'public');
const cacheAge=3600*24*365;
server.on('request'.(request: IncomingMessage, response:ServerResponse) = > {
    const {method,url: path,headers}=request;
    Static servers cannot post
    if(method! ='GET'){
        response.statusCode=405;
        response.end("fake response");
        return;
    }

    const {pathname}=url.parse(path);
    let filename=pathname.substring(1);
    if(filename===' '){
        filename='a.html';/ / home page
    }
    fs.readFile(p.resolve(publicDir,filename),(err,data) = >{
        if(err){
            fs.readFile(p.resolve(publicDir,'404.html'),(err1,data) = >{
                response.statusCode=404;
                response.end(data)
            })
        }else{
            // Set the cache
            response.setHeader('Cache-Control'.`public,max-age=${cacheAge}`) response.end(data); }})}); server.listen(8888);



Copy the code