zoukankan      html  css  js  c++  java
  • 简单服务器的创建(2)

    该系列随笔为本人巩固知识所写,不足之处还请指出
    //
    引入http模块 const http = require('http'); //引入url模块 const url = require('url'); //创建名为app的服务器 const app = http.createServer(); //引入路径模块 const path = require('path'); //引入fs模块 const fs = require('fs'); // 引入第三方模块mime(需要先用npm下载) const mime = require('mime'); // 服务器接受请求 app.on('request', (req, res)=> { //将路径通过url.parse()方法得到,该方法的说明上文已提到 let {pathname, query} = url.parse(req.url, true); // 如果路径是空的,就让他等于主页的地址,反之不变 pathname = pathname == '/' ? '/default.html' : pathname; // 用拼接的方式得到文件在服务器端硬盘的绝对位置 let filepath = path.join(__dirname , 'public' + pathname); // 通过mime.getType()方法可以把filepath位置的html文件中所需的所有文件的格式得到 let type = mime.getType(filepath); //打开文件操作 fs.readFile( filepath, (err, result) => { // 如果有错就退出 if( err != null) { res.end('fault'); return; } // 设置资源的类型 res.writeHead(200, { 'content-type' : type }) // 返回得到的页面 res.end(result); }) }) // 链接端口 app.listen(3000); //是否成功打开的判断 console.log('创建服务器成功');
  • 相关阅读:
    25-k个一组翻转链表 203-移除链表元素 206-反转一个链表
    24. 两两交换链表中的节点
    23-合并K个升序链表
    19-删除链表的倒数第N个节点
    18-四数之和
    21-合并两个有序链表
    双指针
    16-最接近的三数之和
    15-三数之和
    RobotFramework 断言关键字
  • 原文地址:https://www.cnblogs.com/dokom666/p/12884956.html
Copyright © 2011-2022 走看看