Hi, trying to add a few commands to the standard REPL but the naive way via --require=... doesn't seem to work as the module file is loaded before the internal repl object is created. I'm using the usual repl.repl.defineCommand() method. Is there some simple and reliable way to run the definitions after the repl object is ready, other than adding some time delay? Or do I have to build the REPL object myself (and load it via theNODE_REPL_EXTERNAL_MODULE env var)?
#Custom commands for Node.js REPL
13 messages · Page 1 of 1 (latest)
You could (it’s hacky) modify the REPL prototype to perform your extra actions.
(It’s defined at https://github.com/nodejs/node/blob/main/lib/repl.js)
but the code for the REPL is pretty dated (converting it to an ES class is on my long term todo list)
Haha, well, I'm doing it because I'm revisiting JavaScript after a long, long hiatus and toying around with the REPL is a nice way to practice the basics, get an idea about the gotchas and corner cases etc. The commands I wanted to add are simple convenience stuff, like saving a timestamped command log without me having to invent and type out its filename, quick cd, pwd, and some others. I already have a few modules that add some other convenience stuff to other classes/prototypes, but these don't have the timing issue, as all these prototypes already exist when my modules get loaded at node.js startup.
So, you mean like overriding defineDefaultCommands() with my own version that would call the old one and to addition to that also defined my own commands?
Something like that may work
Sounds hacky as hell, but might be doable. Though at that point, I might just cobble up a custom repl instead as it should be just a few lines of code given how the API is designed and should give me control about when its object will start to exist. 🙂
Also, a bit unrelated, but supporting custom functions instead of strings in the single-line prompt would probably need modification of some ef the internals, rigth? Or do you think it might be doable "from the outside" as well? (just in case you happen to have that part in your head, no problem if you don't)
I don’t believe so, that whole API needs a rewrite tbh
Let’s see if I can get started on that tomorrow
Oh, wow. Anyways, thanks for the pointers, I wasn't expecting to get a reply from one of the devs. Really appreciated. 🙂
No problem, let me know if you need anything
Behold the power of JavaScript!
repl.repl.setPrompt({toString: () => process.cwd() + "> "})
// no errer checking, will kill the whole REPL when directory doesn't exist
repl.repl.defineCommand('cd', {
help: 'change current working directory',
action: function(newDir) {
process.chdir(newDir);
repl.repl.displayPrompt();
}
});
(actually, the seemingly hard or even impossible turned out to be easier than the seemingly easy 😄 )