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('创建服务器成功');
  • 相关阅读:
    Docker
    Docker
    log4j日志类的使用
    &times被转义成x的解决方法
    java通用的jdbc数据库操作类
    java一个调用webapi的工具类
    Java 开发杂记
    J2EE名词解释
    C# 进程之间的通讯
    如何捕获全局异常
  • 原文地址:https://www.cnblogs.com/dokom666/p/12884956.html
Copyright © 2011-2022 走看看