PageRenderTime 37ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/node.js

https://github.com/morkai/blanket
JavaScript | 65 lines | 58 code | 4 blank | 3 comment | 4 complexity | 77e9f5e533f7542846ca84a8d3a625cc MD5 | raw file
Possible License(s): MIT
  1. var blanket = require("./blanket").blanket;
  2. function normalizeBackslashes(str) {
  3. return str.replace(/\\/g, '/');
  4. }
  5. //not completed, still needs a lot of work.
  6. module.exports = function(subdir){
  7. var fs = require("fs");
  8. var oldLoader = require.extensions['.js'];
  9. var path = require("path");
  10. //you can pass in a string, a regex, or an array of files
  11. function matchPattern(filename){
  12. if (typeof subdir === 'string'){
  13. return filename.indexOf(normalizeBackslashes(subdir)) > -1;
  14. }else if ( subdir instanceof Array ){
  15. return subdir.some(function(elem){
  16. return filename.indexOf(normalizeBackslashes(elem)) > -1;
  17. });
  18. }else if (subdir instanceof RegExp){
  19. return subdir.test(filename);
  20. }else{
  21. throw Error("Bad file instrument indicator. Must be a string, regex, or array.");
  22. }
  23. }
  24. //find current scripts
  25. require.extensions['.js'] = function(localModule, filename) {
  26. filename = normalizeBackslashes(filename);
  27. if (matchPattern(filename)){
  28. var content = fs.readFileSync(filename, 'utf8');
  29. blanket.instrument({
  30. inputFile: content,
  31. inputFileName: filename
  32. },function(instrumented){
  33. var baseDirPath = normalizeBackslashes(path.dirname(filename))+'/.';
  34. try{
  35. instrumented = instrumented.replace(/require\s*\(\s*("|')\./g,'require($1'+baseDirPath);
  36. //try returning the module without exports first
  37. var ret = eval(instrumented);
  38. //We need to wrap the instrumented code in a closure
  39. //in order to be able to correctly return the
  40. //exports object from the eval
  41. if (typeof ret !== 'undefined'){
  42. var startWrapper = "(function(){\n";
  43. var endWrapper = "\nreturn module.exports; })();";
  44. ret = eval(startWrapper+instrumented+endWrapper);
  45. }
  46. //pass the exports back to the require statement
  47. //that initiated all of this.
  48. localModule.exports = ret;
  49. }
  50. catch(err){
  51. console.log("Error parsing instrumented code: "+err);
  52. }
  53. });
  54. }else{
  55. oldLoader(localModule,filename);
  56. }
  57. };
  58. };