Skip to content

Instantly share code, notes, and snippets.

@fuunnx
Last active March 3, 2016 13:12
Show Gist options
  • Save fuunnx/d0bae44e4bfe13228511 to your computer and use it in GitHub Desktop.
Save fuunnx/d0bae44e4bfe13228511 to your computer and use it in GitHub Desktop.
import Rx from 'rx'
// sources$
const request$ = new Rx.Subject()
const http = require('http')
const fs = require('fs')
const hostname = '127.0.0.1'
const port = 1337
http.createServer(
(req, res) => {
request$.onNext({
body: req,
res
})
})
.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
});
// helpers
const mapRequest = (f) => (request) => ({
...request,
body: f(request.body),
})
const flatMapRequest = (f) => (request) => {
return Rx.Observable.of(request.body)
.flatMap(f)
.map(
body => ({
...request,
body,
})
)
}
function readFile(fileName) {
return new Promise((resolve, reject) => {
fs.readFile(
'./public/' + fileName,
(error, data) => error ? reject(error) : resolve(data)
)
})
}
//main
const response$ = request$
.map(mapRequest(x => 'index.html'))
.flatMap(flatMapRequest(readFile)
//sink$
response$.subscribe(
({
body,
res
}) => {
res.end(body)
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment