How to disable "special commands" in node.js REPL?

686 views Asked by At

Problem Node REPL has some "special commands" like .break and .save. I never use these, but I do very frequently try and paste into the REPL code that's formatted like so:

words.append('ul')
    .classed('my-class', true)
    .selectAll('li.new-class')
    .data((tuple, tupleIdx) => obj[tupleIdx])
    .enter()
    .append('li')
    .classed('new-class', true)
    .text(d => '' + foo(d));

(This is d3.js code but similar things happen when using Promises, a chain of .then(...)s starting on each line.)

Of course node complains about "invalid REPL keyword" when it sees .classed or .then on its own line and proceeds to print a sequence of error messages several screens long.

Tenuous pseudo-workaround I've worked around this with a regexp in Vim that moves any whitespace between closing parens and dots to after the dot (:%s/)\n\(\s*\)\./).\r\1/ for completeness) but this is tedious and often I want to copy-paste from a browser and not switch to Vim to reformat some code.

Question Is there any way to disable node REPL "features" which, while well-intentioned, conflict with standard JavaScript practices, such as lines starting with dots?

Or is this too complicated for a terminal application, and if so, is there a way I can communicate with the node REPL via a browser's JS console (not node-monkey which only handles console.log)

PS. This question is mainly about lines starting with . but another such conflict is _ (worked around thankfully by n_).

3

There are 3 answers

0
starball On BEST ANSWER

You can make your own custom REPL. That option should give you maximal control over how your repl behaves.

Since the main problem here is pasting multi-line code into the default repl, as a workaround, try using the .editor special command.

Enter editor mode (Ctrl+D to finish, Ctrl+C to cancel).

It's also mentioned in the answer to this question about writing multiple lines in the node repl

If you're also interested in saving keystrokes, when entering the editor, autocomplete seems to kick in after typing ".ed" so you can shave off three keystrokes in that sense.

0
Ahmed Fasih On

Here's something tentative: using node-copy-paste, I wrote a tiny module that allows me to paste() the contents of clipboard and evals it after fixing lines starting with ..

This goes in paste.js:

var cp = require('copy-paste'); // npm install node-copy-paste

module.exports = function() {
  return eval(cp.paste().replace(/\n\s*\./g, "."));
};

Then in node REPL, paste = require('./paste'); paste() will make it go. Very brittle but it might solve the problem often enough to be valuable.

0
sarimarton On

You can simply delete the command from the instance:

const replServer = repl.start(/* ... */)
delete replServer.commands.load;

You can even define the whole commands object, take a look at the reference implementation:

https://github.com/nodejs/node/blob/main/lib/repl.js