1.0.36 • Published 2 years ago

nv-server-simple-stream v1.0.36

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

nv-server-simple-stream

  • nv-server-simple-stream
  • simple http server
  • support unix-socket
  • support dynamic change handler
  • support manual mode
  • for testbed using

install

  • npm install nv-server-simple-stream

usage

  const S = require("nv-server-simple-stream").http.simple;

example

 //await S.creat(port_or_unix_sock,handler/*default is empty for manual mode*/,opts)
 var srv = await S.creat(8888)

cfg

> S.DFLT_CFG()
{
  opts: {
    IncomingMessage: [Function: IncomingMessage],
    ServerResponse: [Function: ServerResponse],
    insecureHTTPParser: false,
    maxHeaderSize: 16384
  }
  //----------used when port is undefined
  unix_sock: '___usock___',
  dirname: './',
}
>

set handler

    srv.handler_ = async (req,res) => {
        console.log('AAA')
        let r = await S.reply_with_json(res,{rslt:'recved'});
        return(r)
    }

    ////on client

     # curl http://127.0.0.1:8888/a/b?xx=77
     # {"rslt":"recved"}

change handler without stopping server

    srv.handler_ = async (req,res) => {
        console.log('BBB')
        let r = await S.reply_with_json(res,{rslt:'recved-BBB'});
        return(r)
    }

    # curl http://127.0.0.1:8888/a/b?xx=77
    # {"rslt":"recved-BBB"}
    

check request content

        srv.handler_ = async (req,res) => {
            console.log('CCC')
            let D = await S.extract_req(req);          //----------------->
            console.log(D)
            let r = await S.reply_with_json(res,{rslt:'recved'});
            return(r)
        } 

         # curl http://127.0.0.1:8888/a/b?xx=77

        /*
        > CCC
        {
          remoteAddress: '::ffff:127.0.0.1',
          remotePort: undefined,
          host: '127.0.0.1:8888',
          hostname: '127.0.0.1',
          port: '8888',
          method: 'GET',
          path: '/a/b?xx=77',
          headers: {
            host: '127.0.0.1:8888',
            'user-agent': 'curl/7.58.0',
            accept: '*/*'
          },
          body: <Buffer >
        }
        */

validate request

    srv.handler_ = async (req,res) => {
        console.log('DDD')
        let D = await S.extract_req(req);
        let r;
        if(D.path.includes('77')) {
            r = await S.reply_with_json(res,{rslt:'recved'});
        } else {
            r = await S.reply_with_json(res,{err:'wrong-path'}); //--------------------->
            await S.teardown(req)
        }
        return(r)
    }

    /*
    # curl http://127.0.0.1:8888/a/b?xx=77
    {"rslt":"recved"}


    # curl http://127.0.0.1:8888/a/b?xx=999  //----------------------
    {"err":"wrong-path"}            //------------------------------------------------->
    nv-data-tree-repr#

    */

Manual Mode

  //---must set the handler to a empty function:

  srv.handler_ = async (req,res) => {}


  ##  on client
  /*
    nv-data-tree-repr# curl -v http://127.0.0.1:8888/a/b?xx=999
    *   Trying 127.0.0.1...
    * TCP_NODELAY set
    * Connected to 127.0.0.1 (127.0.0.1) port 8888 (#0)
    > GET /a/b?xx=999 HTTP/1.1
    > Host: 127.0.0.1:8888
    > User-Agent: curl/7.58.0
    > Accept: */*
    >

    //---------------------stucked now wait for server

    */
    

     //on server side, using srv.lst_req_ to check the request ,its a getter

         D = await S.extract_req(srv.lst_req_);

        {
          remoteAddress: '::ffff:127.0.0.1',
          remotePort: 48868,
          host: '127.0.0.1:8888',
          hostname: '127.0.0.1',
          port: '8888',
          method: 'GET',
          path: '/a/b?xx=999',
          headers: {
            host: '127.0.0.1:8888',
            'user-agent': 'curl/7.58.0',
            accept: '*/*'
          },
          body: <Buffer >
        }


    // test send with a stream
       var rs$ = fs.createReadStream("./tst-stream") 
       await S.reply_with_stream(srv.lst_res_,rs$)


    #on client
    
    /*
    < HTTP/1.1 200 OK
    < Content-Type: application/octet-stream
    < Date: Tue, 15 Feb 2022 16:24:39 GMT
    < Connection: keep-alive
    < Keep-Alive: timeout=5
    < Transfer-Encoding: chunked
    <
    111122222
    333344444
    * Connection #0 to host 127.0.0.1 left intact

    */ 

encoding AND dynamic switch callback handle

const S = require("nv-server-simple-stream").http.simple;


(async ()=>{
    var srv = await S.creat(8888);
    ////
    srv.handler_ = async (req,res) => {
        //// init handle
        await S.reply_with_html(res,'<html></html>');   //初次請求handler


        //// switch handle after init                   //切換handler
        srv.handler_ = async (req,res) => {
            let D = await S.extract_req(req);
            let reply_with_stream_with_content_encoding = S.creat_reply_with_stream_with_content_encoding(D);
            let rs$ = fs.createReadStream("./package-lock.json");
            let r = await reply_with_stream_with_content_encoding(res,rs$);
            return(r)
        }
    }
})();

//nginx http:8888->https:8888    for test 'br; which supported by chrome only over https

var res0=await fetch("https://192.168.116.129:8888")  // first get <html></html>


var res=await fetch("https://192.168.116.129:8888")
rslt = await fmt_res(res)
data = await concat_achunk(rslt)

/*
    Connection: keep-alive
    Content-Encoding: br
    Content-Type: application/octet-stream
    Date: Tue, 01 Mar 2022 03:44:26 GMT
    Server: nginx/1.14.0 (Ubuntu)
    Transfer-Encoding: chunked

    rslt = await fmt_res(res)
    data = await concat_achunk(rslt)

    var te = new TextDecoder('utf8')
    JSON.parse(te.decode(data.body))

    {name: 'simple-server', version: '1.0.0', lockfileVersion: 1, requires: true, dependencies: {…}}


*/

METHODS

getter/setter for dynamic change handle

  srv.handler_     

getter: last request AND reply

  //be used in manual mode when handler is empty function 
  srv.lst_req_ 
  srv.lst_res_

API

  • async creat(sock_or_port,handler=DFLT_HANDLER ,cfg=DFLT_CFG())

  • async extract_req(req)

  • set_reply_head_to_bytes(res,code=200,msg='OK',opts={})

  • set_reply_head_to_html(res,code=200,msg='OK',opts={})
  • set_reply_head_to_json(res,code=200,msg='OK',opts={})

  • async send_reply_raw_body(res,data)

  • async send_reply_json_body(res,J)
  • async send_reply_stream_body(res,$rs)

  • async end_reply(res)

  • async reply_with_json (res,J,code=200,msg='OK',opts={})
  • async reply_with_bytes (res,data,code=200,msg='OK',opts={})
  • async reply_with_html(res,data,code=200,msg='OK',opts={})
  • async reply_with_stream (res,rs$,code=200,msg='OK',opts={})
  • async teardown(req,err='not-match')

    {
      DFLT_CFG: [Function: DFLT_CFG],
      DFLT_HANDLER: [AsyncFunction: DFLT_HANDLER],
      set_reply_head_to_bytes: [Function: set_reply_head_to_bytes],
      set_reply_head_to_br_bytes: [Function: set_reply_head_to_br_bytes],
      set_reply_head_to_gzip_bytes: [Function: set_reply_head_to_gzip_bytes],
      set_reply_head_to_compress_bytes: [Function: set_reply_head_to_compress_bytes],
      set_reply_head_to_deflate_bytes: [Function: set_reply_head_to_deflate_bytes],
      send_reply_stream_body_with_content_encoding: [AsyncFunction: send_reply_stream_body_with_content_encoding],
      creat_reply_with_stream_with_content_encoding: [Function: creat_reply_with_stream_with_content_encoding],
    }

LICENSE

  • ISC