Complete the code to start a Node.js REPL session.
const repl = require('[1]'); repl.start();
The Node.js REPL module is named repl. You require it to start an interactive session.
Complete the code to define a custom command in the Node.js REPL.
const repl = require('repl'); const server = repl.start('> '); server.defineCommand('[1]', { help: 'Say hello', action() { console.log('Hello!'); this.displayPrompt(); } });
this.displayPrompt() to show the prompt again.The defineCommand method lets you add a new command. Here, the command is named 'hello'.
Fix the error in the code to evaluate an expression asynchronously in the REPL.
const repl = require('repl'); const server = repl.start('> '); server.eval = function(cmd, context, filename, callback) { Promise.resolve(eval(cmd)).then(result => { callback(null, [1]); }).catch(err => { callback(err); }); };
The callback needs the evaluated result to show it in the REPL output.
Fill both blanks to create a REPL with a custom prompt and exit message.
const repl = require('repl'); const server = repl.start({ prompt: '[1]', useColors: true }); server.on('[2]', () => { console.log('Goodbye!'); process.exit(); });
The prompt sets the REPL prompt string. The close event triggers when the REPL exits.
Fill all three blanks to create a REPL that saves context variables and uses a custom eval function.
const repl = require('repl'); const context = { count: 0 }; function customEval(cmd, context, filename, callback) { try { const result = eval(cmd); callback(null, result); } catch (e) { callback(e); } } const server = repl.start({ prompt: '[1]', eval: [2] }); Object.assign(server.context, [3]);
The prompt is set to '>>> '. The custom eval function is named customEval. The context object is assigned to the REPL context.