Last active
November 14, 2017 22:43
-
-
Save stelf/59345a37da2e236cad24d2f25ea72a94 to your computer and use it in GitHub Desktop.
quick demo of how to mix objectMode with String streams and pipe to web
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // rss stream reader with nodejs and express solution by stelf | |
| const saxStream = require('sax-stream') | |
| const fs = require('fs') | |
| const http = require('http') | |
| const express = require('express') | |
| const { Transform } = require('stream') | |
| const app = express(); | |
| const rssloc = 'http://abcnews.go.com/abcnews/topstories' | |
| app.get('/', (req ,res) => { | |
| res.set({'Content-type': 'text/html'}) | |
| // it is important to instantiate the | |
| // transformer each time, as it gets | |
| // closed after 'previous' stream in a | |
| // chain of pipes emits 'end' | |
| const tolistTransform = new Transform({ | |
| objectMode: true, | |
| transform(obj, encoding, callback) { | |
| this.push(`<li>${obj.value}</li>`); | |
| callback(); | |
| } | |
| }) | |
| http.get(rssloc, im => { | |
| im.pipe(saxStream({strict: true, tag: 'title'})) | |
| .pipe(tolistTransform) | |
| .pipe(res) | |
| // look! we don't even need to 'end' the res | |
| // as it gets automatically 'end'-ed by the | |
| // propagated 'end' of parent streams | |
| // im.on('end', () => res.end()) | |
| }) | |
| }) | |
| app.listen(3001) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment