zoukankan      html  css  js  c++  java
  • NodeJS http 模块

    #4 NodeJS http 模块


    工作目录

    Image

    server.js

    var http = require('http');
    var fs = require('fs');
    var path = require('path');
    var mime = require('mime');
    function send404(response){
         response.writeHead(404,{
              'Content-Type':'text/plain'
         });
         response.write('Error 404 : resource not found.');
         response.end();
    }
    function sendFile(request,response,filePath){
         fs.exists(filePath,function(exists){
              if(!exists){
                   return send404(response);
              }
              fs.readFile(filePath,function(err,data){
                   if(err) send404(response);
                   response.writeHead(200,     {
                        'content-type':mime.lookup(path.basename(filePath))
                   });
                   response.end(data);
              })
         })
    }
    var server = http.createServer(function(request,response){
         var filePath = '';
         if(request.url == '/'){
              filePath = 'public/index.html';
         }else{
              filePath = './public' + request.url;
         }
         sendFile(request,response,filePath);
    });
    server.listen(3000,function(){
         console.log('Server listening on 3000');

    })

    index.html

    Image(13)

    按住Shift键不放,空白处右键,选择Open command windows here

    Image(14)

    执行下图命令

    Image(15)

    看到下图收摊

    Image(16)


  • 相关阅读:
    springMVC-1
    8-IO总结
    7-RandomAccessFile 随机流
    6-对象流(对象的序列化)
    正则表达式语法手册,以及一些实例
    JavaScript的屏幕对象
    js常用正则表达式表单验证代码
    使用 CSS3 实现超炫的 Loading(加载)动画效果
    ajax处理跨域有几种方式
    javascript实现图片延迟加载方法汇总(三种方法)
  • 原文地址:https://www.cnblogs.com/kkun/p/4949014.html
Copyright © 2011-2022 走看看