npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cycle-node-http-server

v2.0.2

Published

A Node HTTP(S) driver for Cycle.js

Downloads

3

Readme

Cycle Node Http Server

Driver and router component for manage HTTP/HTTPS services with Cycle.js

Installation with NPM

npm i cycle-node-http-serve --save

HTTP/HTTPS Driver

makeHttpServerDriver(config)

Create the driver

Arguments

Basic usage


const {run} = require('@cycle/run');
const {makeHttpServerDriver} = require('cycle-node-http-server');

function main(sources){

  const {httpServer} = sources;

  const sinks = {
    
  }
  return sinks;
}

const drivers = {
  httpServer: makeHttpServerDriver()
}

run(main,drivers)

Create a HTTP Server Instance

To create a server instance, we need to send a config stream to the httpServer output. Like this :

   const httpCreate$ = xs.of({
        id: 'http',
        action: 'create',
        port: 1983
    });
    
    const sinks = {
       httpServer: httpCreate$
    }

create action config:

Basic example with HTTPS

     const securedOptions = {
          key: fs.readFileSync(`${__dirname}/certs/key.pem`),
          cert: fs.readFileSync(`${__dirname}/certs/cert.pem`)
     };
     
     const httpsCreate$ = xs.of({
        id: 'https',
        action: 'create',
        port: 1984,
        secured: true,
        securedOptions
    });

Close server instance

To close a server instance we need to send a config stream to the httpServer output.

   const httpClose$ = xs.of({
        id: 'http',
        action: 'close'
    });
    
    const sinks = {
       httpServer: httpClose$
    }

create action config:

  • id : the instance reference name. Needed to select the server stream on input.
  • action:'close' : the action name

Select a server stream with select(id)

Select the server width this specific id

Return Object

   const http = httpServer.select('http');

Get events with event(name)

Get event with name stream from a httpobject.

   const http = httpServer.select('http');
   const httpReady$ = http.events('ready');
   const httpRequest$ = http.events('request');

Return Stream

Event ready

Dispatched when the server is ready to listen.

Returned values :

  • event : 'ready'
  • instanceId : The instance id
  • instance : the original Node.js server object

Event request

Dispatched when the server received a request. See Request object above.

Request object

Properties

  • event : 'request',
  • instanceId : The instance id
  • original : original NodeJS request object,
  • url : request's url,
  • method : request's method (POST,GET,PUT, etc...),
  • headers : request's headers,
  • body : the body request. undefinedby default. See BodyParser middleware
  • response : the response object

Responseobject

Methods

send()

Format response for driver output.

Arguments
  • content : the body response
  • options :
  • statusCode : default 200
  • headers : default null
  • statusMessage : default null

Return formatted object for driver output

json()

Format response in json. See send()

text()

Format response in plain text. See send()

html()

Format response in html. See send()

render()

Format response with the render engine defined in makeHttpServerDriver() options.

redirect()

Format response redirection for driver output.

Arguments
  • path : path to redirect
  • options :
  • statusCode : default 302
  • headers : default null
  • statusMessage : default null

Return formatted object for driver output

Basic Usage


const {run} = require('@cycle/run');
const {makeHttpServerDriver} = require('cycle-node-http-server');

function main(sources){

  const {httpServer} = sources;

  // get http source
  const http = httpServer.select('http');
  // get requests
  const serverRequest$ = http.events('request');

  const httpCreate$ = xs.of({
      id: 'http',
      action: 'create',
      port: 1983
  });
  
  // response formated with a helper response object
  // Response in text format : 'covfefe'
  const response$ = serverRequest$.map( req => req.response.text('covfefe') );

  const sinks = {
    httpServer: xs.merge(httpCreate$,response$)
  }
  return sinks;
}

const drivers = {
  httpServer: makeHttpServerDriver()
}

run(main,drivers)

Routing

A Router component using switch-path

Arguments

Router(sources,routes)

  • sources : Cycle.js sources object with a specific source request$, a stream of http(s) requests.
  • routes : a collection of routes. See switch-path

Return stream

Example

 const {makeHttpServerDriver, Router} = require('cycle-node-http-server');

 function main(sources) {

    const { httpServer } = sources;

    // get http source
    const http = httpServer.select('http');
    // get requests
    const serverRequest$ = http.events('request');

    const router$ = Router({ request$: serverRequest$ }, {
        '/': sources => Page({ props$: xs.of({ desc: 'home' }) }),
        '/user/:id': id => sources => Page({ props$: xs.of({ desc: `user/${id}` }) }),
    })

    const sinks = {
        httpServer: router$.map(c => c.httpServer).flatten(),
    }
    return sinks;
}

 function Page(sources) {
    // request$ is add by the Router to the `sources` object
    const { props$, request$ } = sources;
    const sinks = {
        httpServer: xs.combine(props$, request$).map(([props, req]) => req.response.text(props.desc))
    }
    return sinks;
}

Cooking with middlewares

Here are discribed two usefull express middlewares.

serveStatic

It is used to serve static files ( images, css, etc... )

Basic usage

const serveStatic = require('serve-static');
const {makeHttpServerDriver} = require('cycle-node-http-server');

const drivers = {
  httpServer: makeHttpServerDriver({middlewares:[serveStatic('./public')]})
}

bodyParser

It is used to parse request body and return a full formated body.

Basic usage

const bodyParser = require('body-parser');
const {makeHttpServerDriver} = require('cycle-node-http-server');

const drivers = {
  httpServer: makeHttpServerDriver({
      middlewares: [
          // two parsers used to format body POST request in json
          bodyParser.urlencoded({ extended: true }),
          bodyParser.json()
      ]
  })
}

Using Snabbdom

Snabbdom is the Virtual DOM using by @cycle/dom. It's possible to use it in server side with snabbdom-to-html.

A small helper to use snabbdom with cycle-node-http-server

  const snabbdomInit = require('snabbdom-to-html/init');
  const snabbdomModules = require('snabbdom-to-html/modules');
  const {makeHttpServerDriver} = require('cycle-node-http-server');
    
  export default function vdom(modules=[
          snabbdomModules.class,
          snabbdomModules.props,
          snabbdomModules.attributes,
          snabbdomModules.style
      ]){
      return snabbdomInit(modules);
  }
  
  const drivers = {
    httpServer: makeHttpServerDriver({
        render: vdom()
    })
  }

In main function, snabbdom used with JSX

  const response$ = request$.map( req => req.response.render(
    <div>
      Pouet
    </div>
  ))

License

MIT