Http启动一个html页面

 const http = require('http');
const path = require('path');
const url = require('url');

const readFildeFn = require('./http_readfile.js');
const staticPath = file => path.join(__dirname, 'index', file); //index是文件夹的名字

let server = http.createServer((req, res) => {
    let ourl = url.parse(req.url);
    let pathName = ourl.pathname;
    //console.log(pathName);
    if (pathName == '/favicon.ico') {
        res.end('');
        return;
    }
    pathName = pathName === '/' ? 'index.html' : pathName;
    let extName = path.extname(pathName);
    if (extName) {
        readFildeFn(staticPath(pathName))
            .then(con => {
                res.end(con);
            })
            .catch(error => {
                res.end(JSON.stringify(error));
            });
    } else {
        //请求的是接口
        switch (pathName) {
            case '/api/list':
        }
    }
});
server.listen(8080, () => {
    console.log('服务请求成功');
});

./http_readfile.js

/**
 * 根据路径读取文件
 * 读取文件需要使用异步读取
 * promis => 承诺
 */
const fs = require('fs');

function readFile(filePath) {
    //判断此路径是否存在,如果不存在不能继续执行
    if (!fs.existsSync(filePath)) {
        return;
    }
    return new Promise((resolve, reject) => {
        fs.readFile(filePath, 'utf-8', (error, con) => {
            //读取到文件具体做什么不能写死
            if (error) {
                reject(error);
            } else {
                resolve(con);
            }
        });
    });
}
module.exports = readFile;

你可能感兴趣的:(Http启动一个html页面)