___dataurize.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*******************************************************************************
  2. AToMPM - A Tool for Multi-Paradigm Modelling
  3. Copyright (c) 2011 Raphael Mannadiar (raphael.mannadiar@mail.mcgill.ca)
  4. This file is part of AToMPM.
  5. AToMPM is free software: you can redistribute it and/or modify it under the
  6. terms of the GNU Lesser General Public License as published by the Free Software
  7. Foundation, either version 3 of the License, or (at your option) any later
  8. version.
  9. AToMPM is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
  11. PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with AToMPM. If not, see <http://www.gnu.org/licenses/>.
  14. *******************************************************************************/
  15. /* return a datauri encoding of the resource at the given url */
  16. exports.dataurize =
  17. function(url,callback)
  18. {
  19. var request =
  20. require('http').request(
  21. {'host':url.hostname || '127.0.0.1',
  22. 'port':url.port || 80,
  23. 'path':url.path || '/'},
  24. function(resp)
  25. {
  26. var data = '';
  27. resp.setEncoding('binary');
  28. resp.on('data', function(chunk) {data += chunk;});
  29. resp.on('end',
  30. function()
  31. {
  32. if( resp.statusCode == 200 )
  33. callback(
  34. undefined,
  35. 'data:'+resp.headers['content-type']+';base64,'+
  36. new Buffer(data,'binary').toString('base64'));
  37. else
  38. callback({'statusCode':resp.statusCode, 'reason':data});
  39. });
  40. });
  41. request.on('error',
  42. function(err)
  43. {
  44. callback({'statusCode':0, 'reason':err});
  45. });
  46. request.end();
  47. };