intercept.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /*jshint node: true */
  2. var inserted,
  3. Module = require('module'),
  4. fs = require('fs'),
  5. existingExtFn = Module._extensions['.js'],
  6. amdefineRegExp = /amdefine\.js/;
  7. inserted = "if (typeof define !== 'function') {var define = require('amdefine')(module)}";
  8. //From the node/lib/module.js source:
  9. function stripBOM(content) {
  10. // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  11. // because the buffer-to-string conversion in `fs.readFileSync()`
  12. // translates it to FEFF, the UTF-16 BOM.
  13. if (content.charCodeAt(0) === 0xFEFF) {
  14. content = content.slice(1);
  15. }
  16. return content;
  17. }
  18. //Also adapted from the node/lib/module.js source:
  19. function intercept(module, filename) {
  20. var content = stripBOM(fs.readFileSync(filename, 'utf8'));
  21. if (!amdefineRegExp.test(module.id)) {
  22. content = inserted + content;
  23. }
  24. module._compile(content, filename);
  25. }
  26. intercept._id = 'amdefine/intercept';
  27. if (!existingExtFn._id || existingExtFn._id !== intercept._id) {
  28. Module._extensions['.js'] = intercept;
  29. }