run-repl.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Load the module contained in the current directory (cwd) and start REPL
  2. // NOTE: Calls process.exit() after REPL was closed
  3. var Module = require('module');
  4. var path = require('path');
  5. var repl = require('repl');
  6. var util = require('util');
  7. var location = process.cwd();
  8. var moduleToDebug;
  9. var sampleLine;
  10. var prompt;
  11. try {
  12. loadAndDescribeModuleInCwd();
  13. } catch (e) {
  14. sampleLine = util.format(
  15. 'The module in the current directory was not loaded: %s.',
  16. e.message || e
  17. );
  18. }
  19. startRepl();
  20. //---- Implementation ----
  21. function loadAndDescribeModuleInCwd() {
  22. // Hack: Trick node into changing process.mainScript to moduleToDebug
  23. moduleToDebug = Module._load(location, module, true);
  24. var sample = getSampleCommand();
  25. sampleLine = util.format('You can access your module as `m`%s.', sample);
  26. prompt = getModuleName() + '> ';
  27. }
  28. function startRepl() {
  29. var cmd = process.env.CMD || process.argv[1];
  30. console.log(
  31. '\nStarting the interactive shell (REPL). Type `.help` for help.\n' +
  32. '%s\n' +
  33. 'Didn\'t want to start REPL? Run `%s .` instead.',
  34. sampleLine,
  35. cmd
  36. );
  37. var r = repl.start( { prompt: prompt });
  38. if (moduleToDebug !== undefined)
  39. r.context.m = moduleToDebug;
  40. r.on('exit', onReplExit);
  41. }
  42. function onReplExit() {
  43. console.log('\nLeaving the interactive shell (REPL).');
  44. process.exit();
  45. }
  46. function getModuleName() {
  47. try {
  48. var packageJson = require(path.join(location, 'package.json'));
  49. if (packageJson.name)
  50. return packageJson.name;
  51. } catch (e) {
  52. // ignore missing package.json
  53. }
  54. return path.basename(location);
  55. }
  56. function getSampleCommand() {
  57. var exportedSymbols = Object.keys(moduleToDebug);
  58. if (!exportedSymbols.length) return '';
  59. var sample = exportedSymbols[0];
  60. if (typeof(moduleToDebug[sample]) === 'function')
  61. sample += '()';
  62. return ', e.g. `m.' + sample + '`';
  63. }