url-rewriter.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. var path = require('path');
  2. module.exports = {
  3. process: function(data, options) {
  4. var tempData = [];
  5. var nextStart = 0;
  6. var nextEnd = 0;
  7. var cursor = 0;
  8. for (; nextEnd < data.length; ) {
  9. nextStart = data.indexOf('url(', nextEnd);
  10. if (nextStart == -1)
  11. break;
  12. nextEnd = data.indexOf(')', nextStart + 4);
  13. if (nextEnd == -1)
  14. break;
  15. tempData.push(data.substring(cursor, nextStart));
  16. var url = data.substring(nextStart + 4, nextEnd).replace(/['"]/g, '');
  17. tempData.push('url(' + this._rebased(url, options) + ')');
  18. cursor = nextEnd + 1;
  19. }
  20. return tempData.length > 0 ?
  21. tempData.join('') + data.substring(cursor, data.length) :
  22. data;
  23. },
  24. _rebased: function(url, options) {
  25. var specialUrl = url[0] == '/' ||
  26. url.substring(url.length - 4) == '.css' ||
  27. url.indexOf('data:') === 0 ||
  28. /^https?:\/\//.exec(url) !== null ||
  29. /__\w+__/.exec(url) !== null;
  30. var rebased;
  31. if (specialUrl)
  32. return url;
  33. if (options.absolute) {
  34. rebased = path
  35. .resolve(path.join(options.fromBase, url))
  36. .replace(options.toBase, '');
  37. } else {
  38. rebased = path.relative(options.toBase, path.join(options.fromBase, url));
  39. }
  40. return process.platform == 'win32' ?
  41. rebased.replace(/\\/g, '/') :
  42. rebased;
  43. }
  44. };