-
-
Save m5m1th/a34843e034716cb24af8 to your computer and use it in GitHub Desktop.
var hyperquest = require('hyperquest'); | |
var result; | |
module.exports = function downloadUtf8FileIntoString(url, cb) { | |
if (!url) return cb(Error('url is required')); | |
result = ''; | |
hyperquest(url) | |
.pipe(function (chunk, enc, tCb) { | |
result += chunk.toString('utf8'); // binary to utf8 | |
tCb(); | |
}) | |
.on('finish', function () { | |
cb(result); // all done | |
}) | |
} |
Answers!
4. Use setImmediate
for callbacks. Create errors with new Error
.
5. result
is declared outside of this func. If you call this twice to download two files at the same time, the results will overwrite each other.
7. Wrong way to do streams. Instead, catch the data event: http://nodejs.org/api/stream.html#stream_event_data
8. UTF8 chars can span multiple bytes. A given chunk might end in the middle of a UTF8 char, corrupting your data. Either buffer up all the responses and do the UTF8 decoding at the end or let node streams decode it for you with stream.setEncoding('utf8')
http://nodejs.org/api/stream.html#stream_readable_setencoding_encoding
11. Readable streams use end
instead of finish
12. Should be cb(null, result)
. Also, avoid useless comments.
13. No handler for onerror
event. If the connection is interrupted, your callback will never get called and this thread of execution will stall. (Thread isn't the right word here ... is there one?)
14. Missing semicolon ;)
- Isn't true for all streams: see: http://nodejs.org/api/stream.html#stream_event_finish
You're right -- updated to be more specific
Email me your answers by Friday 12-12 at 11:59PM