___dataurize.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /* This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
  2. * Copyright 2011 by the AToMPM team and licensed under the LGPL
  3. * See COPYING.lesser and README.md in the root of this project for full details
  4. */
  5. /* return a datauri encoding of the resource at the given url */
  6. exports.dataurize =
  7. function(url,callback)
  8. {
  9. var request =
  10. require('http').request(
  11. {'host':url.hostname || '127.0.0.1',
  12. 'port':url.port || 80,
  13. 'path':url.path || '/'},
  14. function(resp)
  15. {
  16. var data = '';
  17. resp.setEncoding('binary');
  18. resp.on('data', function(chunk) {data += chunk;});
  19. resp.on('end',
  20. function()
  21. {
  22. if( resp.statusCode == 200 )
  23. callback(
  24. undefined,
  25. 'data:'+resp.headers['content-type']+';base64,'+
  26. new Buffer(data,'binary').toString('base64'));
  27. else
  28. callback({'statusCode':resp.statusCode, 'reason':data});
  29. });
  30. });
  31. request.on('error',
  32. function(err)
  33. {
  34. callback({'statusCode':0, 'reason':err});
  35. });
  36. request.end();
  37. };