{"id":21610531,"url":"https://github.com/mrpierrot/cycle-node-http-server","last_synced_at":"2025-04-11T05:22:28.491Z","repository":{"id":102554355,"uuid":"94106067","full_name":"mrpierrot/cycle-node-http-server","owner":"mrpierrot","description":"Driver and router component for manage HTTP/HTTPS services with Cycle.js","archived":false,"fork":false,"pushed_at":"2017-09-06T08:28:17.000Z","size":31,"stargazers_count":6,"open_issues_count":1,"forks_count":3,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-25T03:25:44.306Z","etag":null,"topics":["cyclejs","http-server","nodejs"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mrpierrot.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-06-12T14:33:23.000Z","updated_at":"2021-09-15T15:35:59.000Z","dependencies_parsed_at":null,"dependency_job_id":"2970a2ee-feb8-4534-ad99-874a0a61d79f","html_url":"https://github.com/mrpierrot/cycle-node-http-server","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mrpierrot%2Fcycle-node-http-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mrpierrot%2Fcycle-node-http-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mrpierrot%2Fcycle-node-http-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mrpierrot%2Fcycle-node-http-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mrpierrot","download_url":"https://codeload.github.com/mrpierrot/cycle-node-http-server/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248346363,"owners_count":21088445,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cyclejs","http-server","nodejs"],"created_at":"2024-11-24T21:08:33.671Z","updated_at":"2025-04-11T05:22:28.469Z","avatar_url":"https://github.com/mrpierrot.png","language":"JavaScript","funding_links":[],"categories":["Libraries"],"sub_categories":["Drivers"],"readme":"# Cycle Node Http Server\n\nDriver and router component for manage HTTP/HTTPS services with Cycle.js\n\n## Installation with NPM\n\n`npm i cycle-node-http-serve --save`\n\n## HTTP/HTTPS Driver\n\n### `makeHttpServerDriver(config)`\n\nCreate the driver\n\n**Arguments**\n\n- `config` with specifics options\n  - `middlewares : Array` : array of [express compatible middlewares](http://expressjs.com/en/guide/using-middleware.html)    like [serveStatic](https://github.com/expressjs/serve-static) or [bodyParser](https://github.com/expressjs/body-parser)\n  - `render: (template) =\u003e template` : a template engine renderer, call with `req.response.render(template)`\n\n#### Basic usage\n\n```js\n\nconst {run} = require('@cycle/run');\nconst {makeHttpServerDriver} = require('cycle-node-http-server');\n\nfunction main(sources){\n\n  const {httpServer} = sources;\n\n  const sinks = {\n\n  }\n  return sinks;\n}\n\nconst drivers = {\n  httpServer: makeHttpServerDriver()\n}\n\nrun(main,drivers)\n\n```\n\n### Create a HTTP Server Instance\n\nTo create a server instance, we need to send a config stream to the httpServer output.\nLike this :\n\n```js\n   const httpCreate$ = xs.of({\n        id: 'http',\n        action: 'create',\n        port: 1983\n    });\n\n    const sinks = {\n       httpServer: httpCreate$\n    }\n```\n\n**create action config:**\n\n- `id` : the instance reference name. Needed to select the server stream on input.\n- `action:'create'` : the action name\n- `port` : see [server.listen([port][, hostname][, backlog][, callback]) on NodeJS Api](https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback)\n- `hostname` : see [server.listen([port][, hostname][, backlog][, callback]) on NodeJS Api](https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback)\n- `backlog` : see [server.listen([port][, hostname][, backlog][, callback]) on NodeJS Api](https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback)\n- `handle` : see [server.listen(handle[, callback]) on NodeJS Api](https://nodejs.org/api/http.html#http_server_listen_handle_callback)\n- `path` : see [server.listen(path[, callback]) on NodeJS Api](https://nodejs.org/api/http.html#http_server_listen_path_callback)\n- `secured` : set at true to create a HTTPS server.\n- `securedOptions` : Needed if `secured`is `true` see [Node HTTPS createServer options](https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener)\n- `middlewares : Array` : array of [express compatible middlewares](http://expressjs.com/en/guide/using-middleware.html)    like [serveStatic](https://github.com/expressjs/serve-static) or [bodyParser](https://github.com/expressjs/body-parser)\n\n**Basic example with HTTPS**\n\n```js\n     const securedOptions = {\n          key: fs.readFileSync(`${__dirname}/certs/key.pem`),\n          cert: fs.readFileSync(`${__dirname}/certs/cert.pem`)\n     };\n\n     const httpsCreate$ = xs.of({\n        id: 'https',\n        action: 'create',\n        port: 1984,\n        secured: true,\n        securedOptions\n    });\n\n```\n\n### Close server instance\n\nTo close a server instance we need to send a config stream to the httpServer output.\n\n```js\n   const httpClose$ = xs.of({\n        id: 'http',\n        action: 'close'\n    });\n\n    const sinks = {\n       httpServer: httpClose$\n    }\n```\n\n**create action config:**\n\n- `id` : the instance reference name. Needed to select the server stream on input.\n- `action:'close'` : the action name\n\n### Select a server stream with `select(id)`\n\nSelect the server width this specific `id`\n\n**Return Object**\n\n```js\n   const http = httpServer.select('http');\n```\n\n### Get events with `event(name)`\n\nGet event with `name` stream from a `http`object.\n\n```js\n   const http = httpServer.select('http');\n   const httpReady$ = http.events('ready');\n   const httpRequest$ = http.events('request');\n```\n**Return Stream**\n\n#### Event `ready`\n\nDispatched when the server is ready to listen.\n\n**Returned values :**\n- `event` : `'ready'`\n- `instanceId` : The instance id\n- `instance` : the original Node.js server object\n\n#### Event `request`\n\nDispatched when the server received a request.\nSee `Request` object above.\n\n### `Request` object\n\n#### Properties\n\n- `event` : `'request'`,\n- `instanceId` : The instance id\n- `original` : original NodeJS request object,\n- `url` : request's url,\n- `method` : request's method (POST,GET,PUT, etc...),\n- `headers` : request's headers,\n- `body` : the body request. `undefined`by default. See [BodyParser middleware](https://github.com/expressjs/body-parser)\n- `response` : the response object\n\n### `Response`object\n\n#### Methods\n\n##### `send()`\n\nFormat response for driver output.\n\n###### Arguments\n\n- `content` : the body response\n- `options` :\n - `statusCode` : default `200`\n - `headers` : default `null`\n - `statusMessage` : default `null`\n\n**Return formatted object for driver output**\n\n##### `json()`\n\nFormat response in json.\nSee `send()`\n\n##### `text()`\n\nFormat response in plain text.\nSee `send()`\n\n##### `html()`\n\nFormat response in html.\nSee `send()`\n\n##### `render()`\n\nFormat response with the render engine defined in `makeHttpServerDriver()` options.\n\n##### `redirect()`\n\nFormat response redirection for driver output.\n\n###### Arguments\n\n- `path` : path to redirect\n- `options` :\n - `statusCode` : default `302`\n - `headers` : default `null`\n - `statusMessage` : default `null`\n\n**Return formatted object for driver output**\n\n### Basic Usage\n\n```js\n\nconst {run} = require('@cycle/run');\nconst {makeHttpServerDriver} = require('cycle-node-http-server');\n\nfunction main(sources){\n\n  const {httpServer} = sources;\n\n  // get http source\n  const http = httpServer.select('http');\n  // get requests\n  const serverRequest$ = http.events('request');\n\n  const httpCreate$ = xs.of({\n      id: 'http',\n      action: 'create',\n      port: 1983\n  });\n\n  // response formated with a helper response object\n  // Response in text format : 'covfefe'\n  const response$ = serverRequest$.map( req =\u003e req.response.text('covfefe') );\n\n  const sinks = {\n    httpServer: xs.merge(httpCreate$,response$)\n  }\n  return sinks;\n}\n\nconst drivers = {\n  httpServer: makeHttpServerDriver()\n}\n\nrun(main,drivers)\n\n```\n\n## Routing\n\nA Router component using [switch-path](https://github.com/staltz/switch-path)\n\n**Arguments**\n\n`Router(sources,routes)`\n\n- `sources` :  Cycle.js sources object with a specific source `request$`, a stream of http(s) requests.\n- `routes` : a collection of routes. See [switch-path](https://github.com/staltz/switch-path)\n\n**Return stream**\n\n### Example\n\n```js\n const {makeHttpServerDriver, Router} = require('cycle-node-http-server');\n\n function main(sources) {\n    const { httpServer } = sources;\n\n    // get http source\n    const http = httpServer.select('http');\n\n    // create the http server\n    const httpCreate$ = xs.of({\n        id: 'http',\n        action: 'create',\n        port: 1983,\n    });\n\n    // get requests\n    const serverRequest$ = http.events('request');\n\n    // routing\n    const router$ = Router({ request$: serverRequest$ }, {\n        '/': sources =\u003e Page(Object.assign({}, sources, { props$: xs.of({ desc: 'home' }) })),\n        '/user/:id': id =\u003e sources =\u003e Page(Object.assign({}, sources, { props$: xs.of({ desc: `user/${id}` }) })),\n    });\n\n    const sinks = {\n        httpServer: xs.merge(httpCreate$, router$.map(c =\u003e c.httpServer).flatten()),\n    };\n    return sinks;\n}\n\n function Page(sources) {\n    const { props$, request$ } = sources;\n    const sinks = {\n        httpServer: xs.combine(props$, request$).map(([props, req]) =\u003e req.response.text(props.desc))\n    }\n    return sinks;\n}\n```\n\n## Cooking with middlewares\n\nHere are discribed two usefull express middlewares.\n\n### [serveStatic](https://github.com/expressjs/serve-static)\n\nIt is used to serve static files ( images, css, etc... )\n\n**Basic usage**\n\n```js\nconst serveStatic = require('serve-static');\nconst {makeHttpServerDriver} = require('cycle-node-http-server');\n\nconst drivers = {\n  httpServer: makeHttpServerDriver({middlewares:[serveStatic('./public')]})\n}\n\n```\n\n### [bodyParser](https://github.com/expressjs/body-parser)\n\nIt is used to parse request body and return a full formated body.\n\n**Basic usage**\n\n```js\nconst bodyParser = require('body-parser');\nconst {makeHttpServerDriver} = require('cycle-node-http-server');\n\nconst drivers = {\n  httpServer: makeHttpServerDriver({\n      middlewares: [\n          // two parsers used to format body POST request in json\n          bodyParser.urlencoded({ extended: true }),\n          bodyParser.json()\n      ]\n  })\n}\n\n```\n\n## Using [Snabbdom](https://github.com/snabbdom/snabbdom)\n\nSnabbdom is the Virtual DOM using by @cycle/dom. It's possible to use it in server side with [snabbdom-to-html](https://github.com/snabbdom/snabbdom-to-html).\n\nA small helper to use `snabbdom` with `cycle-node-http-server`\n\n```js\n  const snabbdomInit = require('snabbdom-to-html/init');\n  const snabbdomModules = require('snabbdom-to-html/modules');\n  const {makeHttpServerDriver} = require('cycle-node-http-server');\n\n  export default function vdom(modules=[\n          snabbdomModules.class,\n          snabbdomModules.props,\n          snabbdomModules.attributes,\n          snabbdomModules.style\n      ]){\n      return snabbdomInit(modules);\n  }\n\n  const drivers = {\n    httpServer: makeHttpServerDriver({\n        render: vdom()\n    })\n  }\n\n```\nIn `main` function, snabbdom used with JSX\n\n```js\n  const response$ = request$.map( req =\u003e req.response.render(\n    \u003cdiv\u003e\n      Pouet\n    \u003c/div\u003e\n  ))\n\n```\n\n## License\n\n**MIT**\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmrpierrot%2Fcycle-node-http-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmrpierrot%2Fcycle-node-http-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmrpierrot%2Fcycle-node-http-server/lists"}