NetworkAgent.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. var fs = require('fs');
  2. var path = require('path');
  3. var dataUri = require('strong-data-uri');
  4. function NetworkAgent() {
  5. }
  6. NetworkAgent.prototype.loadResourceForFrontend = function(params, done) {
  7. if (/^data:/.test(params.url)) {
  8. try {
  9. done(null, {
  10. statusCode: 200,
  11. headers: {},
  12. content: dataUri.decode(params.url).toString('ascii')
  13. });
  14. } catch (err) {
  15. done(err);
  16. }
  17. return;
  18. }
  19. loadFileResource(params, done);
  20. };
  21. function loadFileResource(params, done) {
  22. var match = params.url.match(/^file:\/\/(.*)$/);
  23. if (!match) {
  24. return done(
  25. 'URL scheme not supported by Network.loadResourceForFrontend: ' +
  26. params.url);
  27. }
  28. var filePath = match[1];
  29. if (process.platform == 'win32') {
  30. // On Windows, we should receive '/C:/path/to/file'.
  31. if (!/^\/[a-zA-Z]:\//.test(filePath)) {
  32. return done('Invalid windows path: ' + filePath);
  33. }
  34. // Remove leading '/' and replace all other '/' with '\'
  35. filePath = filePath.slice(1).split('/').join(path.sep);
  36. }
  37. // ensure there are no ".." in the path
  38. filePath = path.normalize(filePath);
  39. fs.readFile(
  40. filePath,
  41. { encoding: 'utf8' },
  42. function(err, content) {
  43. if (err) return done(err);
  44. done(null, {
  45. statusCode: 200,
  46. headers: {},
  47. content: content
  48. });
  49. }
  50. );
  51. }
  52. NetworkAgent.prototype.setUserAgentOverride = function(params, done) {
  53. done(null, {});
  54. };
  55. exports.NetworkAgent = NetworkAgent;