0
点赞
收藏
分享

微信扫一扫

node.js学习记录——简单的web服务器

楚木巽 2022-02-19 阅读 54
//导入http模块
const http = require('http');
///导入path模块
const path = require('path');
//导入fs模块
const fs = require('fs');
//创建服务器实例
const server = http.createServer();
//绑定request事件,监听请求
server.on('request', function (request, response) {
    //url从第一个/开始后边的内容,包括/
    const url = request.url;
    //拼接路径
    let fpath = '';
    if (url === '/') {
        fpath = path.join(__dirname, '/files/index.html');
    } else {
        fpath = path.join(__dirname, url);
    }
    //读取文件
    fs.readFile(fpath, 'utf-8', (err, data) => {
        if (err) return response.end('404 Not Found');
        response.end(data);
    })
    //response.setHeader('Content-Type', 'text/html; charset=utf-8');

});
//启动服务器
server.listen(80, function () {

    console.log('server runnning at http://127.0.0.1:80');
});

确实比较简陋

举报

相关推荐

0 条评论