Skip to content

Instantly share code, notes, and snippets.

@m5m1th
Created December 5, 2014 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save m5m1th/a34843e034716cb24af8 to your computer and use it in GitHub Desktop.
Save m5m1th/a34843e034716cb24af8 to your computer and use it in GitHub Desktop.
Dev Challenge! What are all the issues with this code? Hint: there are several.
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
})
}
@m5m1th
Copy link
Author

m5m1th commented Dec 5, 2014

Email me your answers by Friday 12-12 at 11:59PM

@m5m1th
Copy link
Author

m5m1th commented Dec 17, 2014

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 ;)

@maxnachlinger
Copy link

@m5m1th
Copy link
Author

m5m1th commented Dec 17, 2014

You're right -- updated to be more specific

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment