How to change the repl prompt of node.js? - node.js

node.js's default repl prompt is >, I sometimes type shell commands into it. In order to easily distinguish it from other programming language repl's and shell prompts, I would like to change it to something like node >. Is it possible, or is there any better practice on this problem?

Create a small node program which fires up a REPL and specifies prompt: 'node >' in the options hash.
See docs here.
// repl.js
const repl = require('repl');
var replServer = repl.start({prompt: 'node > '});
$ node repl.js
node >

Related

NodeJS REPL double echoing input, making it hard to use

When I use the NodeJS repl on linux, everything I type is echoed twice. If I start it up like this:
$ node
Welcome to Node.js v16.11.0.
Type ".help" for more information.
> let repl;
undefined
> import("repl").then(module => { repl = module });
Promise {
<pending>,
[Symbol(async_id_symbol)]: 294,
[Symbol(trigger_async_id_symbol)]: 283,
[Symbol(destroyed)]: { destroyed: false }
}
> let f = repl.start();
> undefined
>
Now everything that I type is doubled up. If I type the letter d, it shows dd. This is preventing me from creating my own REPL setup script.
What am I doing wrong here?
When you start node.js in a terminal without passing a javascript file, by default node actually creates a REPL instance behind the scenes to give you something to interact with in your terminal. So by importing and starting another REPL you now have two REPL instances reading stdin and so you get twice the echo of stdin to stdout.
You can access the default running REPL by running this.repl in a newly opened node terminal. If you want only your own REPL to run, I would recommend declaring your REPL in a javascript file and then executing that file with the node runtime instead.

Im trying to reduplicate the shelljs exec type execution in node

I was using shelljs before where i used to call a command like so:
require('shelljs/global');
let res = exec('echo hello').stdout
But I would like to achieve this in node without relying on shelljs.
Thing is I've found examples with node and I'm having trouble with quite a few of them.
Thanks for the help
The ultra simple answer is use the synchronous version of exec. The stdout won't appear as the command runs and the result won't have the nice properties shelljs provides, just the stdout data
const { execSync } = require('child_process')
const exec = (cmd) => execSync(cmd).toString()
const res = exec('echo "hello there"')
The full shelljs implementation is in exec.js, which runs the command via exec-child.js script to enable the live output + capture to variables for a synchronous exec. It depends on the features you require as to how complex the solution becomes.

How can I use readline-sync npm repository with WebStorm?

I wrote the following code using 'readline-sync' dependency.
var readlineSync = require('readline-sync');
function main() {
printMenu();
var userName = readlineSync.question('Please enter your choice:');
console.log(userName);
}
main();
I ran this code from WebStorm trying to use the WebStorm console window.
I got the error:
Error: The current environment doesn't support interactive reading
from TTY. stty: when specifying an output style, modes may not be set
When I run it from linux terminal the code works with no error. I understand from the error message that 'readline-sync' cannot work from WebStorm console. Do you have any idea how to solve it?
I found out the answer.
type in WebStorm terminal:
$ node --debug-brk
Web storm will give you the port number the debugger is listening to. On my machine it was 5858. Then press 'Ctrl+C'.
Create a new debugging configuration as the following one:
In WebStorm terminal type again: "$ node --debug-brk main.js "
put a breakpoint somewhere.
Click the debugging icon
Happy Debugging!

Command line for running server

I have a Node server which I would like to debug. Once I've started the server
node server.js
I want to execute functions defined in server.js from a command line. The usual Node REPL "blocks" after the server has started.
For example, if server.js defines the function addBlogPost I want to locally call addBlogPost() and observe changes in the database without passing through a GUI.
Is there an easy way to do this?
You can use the repl module to create a new REPL instance:
repl = require("repl")
r = repl.start("node> ")
r.context.pause = pauseHTTP;
r.context.resume = resumeHTTP;
Now inside the REPL you can use pause() to call pauseHTTP() and resume() to call resumeHTTP().

Start up script for node.js repl

Is there a way configure node.js's repl? I want to require jquery and underscore automatically whenever the repl starts. Is there a file (noderc?) that node.js loads when it starts the repl?
The equivalent in Python is to edit ~/.ipython/ipy_user_conf.py with:
import_mod('sys os datetime re itertools functools')
I don't know of any such configuration file, but if you want to have modules foo and bar be available in a REPL, you can create a file myrepl.js containing:
var myrepl = require("repl").start();
["foo", "bar"].forEach(function(modName){
myrepl.context[modName] = require(modName);
});
and you when you execute it with node myrepl.js you get a REPL with those modules available.
Armed with this knowledge you can put #!/path/to/node at the top and make it executable directly, or you could modify your version of the repl.js module (source available at https://github.com/joyent/node/blob/master/lib/repl.js for inspection) or whatever :)
Feb 2017 - whilst I agree with the accepted answer, wished to add a little more commentary here.
Like to setup as follows (from home directory on my Mac)
.node
├── node_modules
│   ├── lodash
│   └── ramda
├── package.json
└── repl.js
Then repl.js may look like as follows:
const repl = require('repl');
let r = repl.start({
ignoreUndefined: true,
replMode: repl.REPL_MODE_STRICT
});
r.context.lodash = require('lodash');
r.context.R = require('ramda');
// add your dependencies here as you wish..
And finally, put an alias into your .bashrc or .zshrc file etc (depending on your shell prefs) - something like:
alias noder='node ~/.node/repl.js'
Now, to use this configuration, you just have to type noder from the command line. Above, I also specified that I'd always like to be in strict mode, and do not want undefined printed to the console for declarations etc.
For up-to-date information on repl and in particular repl.start options see here
I tried this today but .start required an argument. Also I think the useGlobal:true was important. I wound up using:
var myrepl=require('repl').start({useGlobal:true});
myrepl.context['myObj']=require('./myObject');
Saving this code in test.js I could do a node test.js then access myObj in REPL.
Might be a newer feature of Node.js (since this question is four years old), but you can load and save repl history like ipython.
.break - While inputting a multi-line expression, sometimes you get lost or just don't care about completing it. .break will start over.
.clear - Resets the context object to an empty object and clears any multi-line expression.
.exit - Close the I/O stream, which will cause the REPL to exit.
.help - Show this list of special commands.
.save - Save the current REPL session to a file
.save ./file/to/save.js
.load - Load a file into the current REPL session.
.load ./file/to/load.js
I can't figure out how to execute this automatically when starting the shell, but .load something is convenient enough for me at the moment.
Keeping things simple here's what I clabbered up.
repl.js:
// things i want in repl
global.reload = require('require-nocache')(module) // so I can reload modules as I edit them
global.r = require('ramda') // <3 http://ramdajs.com/
// launch, also capture ref to the repl, in case i want it later
global.repl = require('repl').start()
I can invoke this with node repl which feels right, and I don't care about globals, because I am just messin' around in the repl.

Resources