json.js 571 B

12345678910111213141516171819202122
  1. 'use strict';
  2. module.exports = function parseJSON(res, fn){
  3. res.text = '';
  4. res.setEncoding('utf8');
  5. res.on('data', chunk => {
  6. res.text += chunk;
  7. });
  8. res.on('end', () => {
  9. try {
  10. var body = res.text && JSON.parse(res.text);
  11. } catch (e) {
  12. var err = e;
  13. // issue #675: return the raw response if the response parsing fails
  14. err.rawResponse = res.text || null;
  15. // issue #876: return the http status code if the response parsing fails
  16. err.statusCode = res.statusCode;
  17. } finally {
  18. fn(err, body);
  19. }
  20. });
  21. };