replace-log.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. var path = require('path')
  2. var fs = require('fs')
  3. var redeyed = require('..')
  4. var vm = require('vm')
  5. var samplePath = path.join(__dirname, 'sources', 'log.js')
  6. var origCode = fs.readFileSync(samplePath, 'utf-8')
  7. var kinds = [ 'silly', 'info', 'warn', 'error' ]
  8. function replaceConsole(s, info) {
  9. var code = info.code
  10. var idx = info.tokenIndex
  11. var tokens = info.tokens
  12. var next = tokens[idx + 1].value
  13. var kind = tokens[idx + 2].value
  14. var openParen = tokens[idx + 3].value
  15. var firstArgTkn = tokens[idx + 4]
  16. var argIdx = idx + 3
  17. var open
  18. var tkn
  19. if (kind === 'log') kind = 'silly'
  20. // not a console.xxx(...) statement? -> just return original
  21. if (next !== '.' || !~kinds.indexOf(kind) || openParen !== '(') return s
  22. // skip past arguments to console.xxx all args from ( to )
  23. open = 1
  24. while (open) {
  25. tkn = tokens[++argIdx]
  26. // count open parens vs. closed ones to handle things like console.log(new Error('..'));
  27. if (tkn.value === '(') open++
  28. if (tkn.value === ')') open--
  29. }
  30. // tkn now is the last closing paren
  31. var argsIncludingClosingParen = code.slice(firstArgTkn.range[0], tkn.range[1])
  32. var result = 'log.' + kind + '("main-logger", ' + argsIncludingClosingParen
  33. // tell redeyed to skip the entire console.xxx(..) statement since we are replacing it all
  34. return { replacement: result, skipPastToken: tkn }
  35. }
  36. function transformAndRun() {
  37. var config = {
  38. Identifier: { console: replaceConsole }
  39. }
  40. var code = redeyed(origCode, config).code
  41. var context = vm.createContext({ require: require })
  42. console.log('Original code:\n', origCode)
  43. console.log('\nlog calls replaced:\n', code)
  44. console.log('\nLets run it:')
  45. vm.runInContext(code, context, 'transformed-log.vm')
  46. }
  47. transformAndRun()