UNPKG

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