How to run NodeJS REPL Inside a Function [Practical Examples]


Written by - Deepak Prasad

What is NodeJS REPL?

The NodeJS REPL(Read-Eval-Print-Loop) server provides a programming environment like a Linux shell where a user can evaluate JavaScript expressions and gain access to node modules. The repl module is a REPL implementation provided by NodeJS. It can be used as a standalone application or included in other applications. This article explores how you can run a NodeJS REPL inside a function and provides practical examples.

 

Prerequisites

Before using REPL, you should have a NodeJS environment set up. Run node -v  to check if you have Node installed. If not, follow this tutorial on how to install NodeJS in your working environment. You should also have a good understanding of JavaScript concepts and have a basic understanding of how to use the terminal

 

How to Start the REPL

The repl module can be accessed using `require’:

const repl = require(‘repl’)

Before understanding how you can use NodeJS repl in a function, you need to first understand how the REPL works. In order to work with REPL, type the following command in your terminal to start it.

node 

You should see the following.

node
>

From this terminal, you are now able to write any JavaScript code in the prompt and the output will be displayed right in the terminal.

To exit the REPL, run the following command.

.exit

 

Running NodeJS REPL Inside a Function

Now that you have seen how to start a REPL server, let’s write a function that starts the REPL when it is executed.

If you still have the REPL running, exit it. Create a JavaScript file and open it with a text editor of your choice. You can name it node-repl.js

Next, create a NodeJS server, to enable you to run the function you will be creating.

In node-repl.js, add the following.

const http = require('http');
const requestListener = function (req, res) {
  res.end('Hello, World!');
}
const server = http.createServer(requestListener);
server.listen(3000);

Next, add a function that starts repl. Modify your app.js file to look like below.

const http = require('http'); 
const repl = require('repl') 
function app() {    
  repl.start() 
} 
app() 
const requestListener = function (req, res) {   
  res.end('Hello, World!');
} 
const server = http.createServer(requestListener); server.listen(3000);

In the above code, you have imported the repl module, defined a function and called the start method on the repl module. Finally,  you are calling the app() function.

To execute the file, open your terminal and run the following command.

node node-repl.js

You might have noticed that using ‘.exit’ does not stop the NodeJS instance. You can configure repl.start() to also exit your application when you stop REPL.

Modify the app function as below.

function app() {
   repl.start().on('exit', () => { process.exit(); });
}

Now, if you type, .exit, your application will also stop executing.

repl.start() accepts an object of options that can have the following values.

  • prompt - this is the input prompt to display.
  • input - the readable stream from which input will be read.
  • output - the writable stream to which output will be written.
  • terminal - a boolean that determines whether a stream should be treated like a TTY terminal.
  • Eval - specifies the function to be used to eval each line.
  • useColors - a boolean that specifies whether the output should have color.
  • ignoreUndefined - a boolean that determines whether an undefined return value will be outputted.

 

Examples of How to Run a NodeJS REPL Inside a Function

The following are some examples that illustrate how you can use the repl module in your application.

 

Accessing a Variable in REPL

You can access any variable that exists in the global scope by assigning it to the context object provided by each repl instance.

function app() {
  repl.start().context.msg = "Message"
}
app()

Now when you run your application, and type ‘msg’, you should be able to see the string ‘Message’

> msg
‘Message’

Context properties like 'msg', can be modified by default. For instance, try to assign a different string to the msg variable like below.

> msg = ‘Modified Message’
‘Modified Message’

If you want a read-only variable, you have to specify read-only globals by defining the context properties using Object.defineProperty like below.

function app() {
 const replServer = repl.start()
 Object.defineProperty(replServer.context, 'msg', {
   configurable: false,
   enumerable: true,
   value: 'Message'
 });
}
app()

 

Invoke a function on REPL

The defineCommand() method can be used to invoke a function when a specified command is processed. This method accepts two arguments, a keyword, and cmd. The keyword is the command while cmd is the function that will be invoked.

function app() {
 const replServer = repl.start()
 replServer.defineCommand("sayhello", {
   help: "Say hello",
   action(name) {
     this.clearBufferedCommand();
     console.log(`Hello, ${name}!`);
     this.displayPrompt();
   },
 });
}
app()

In the above function, you are setting ‘sayhello’ as the command keyword. To process the command, you prefix it with a period like, ‘.sayhello’ and press enter. A cmd argument is an object with help, which specifies the text that will be displayed when .help is run and the action which is the function that will be executed. The function accepts a name argument. To execute it, run the following command.

> .sayhello your-name
Hello your-name

You could also pass just the function as the cmd argument.The above function can therefore be written as:

function app() {
 const replServer = repl.start()
 replServer.defineCommand("sayhello", function sayhello(name) {
   this.clearBufferedCommand();
   console.log(`Hello, ${name}!`);
   this.displayPrompt();
 });
}
app()

 

Customizing NodeJS REPL Output

When using REPL you can customize the appearance of your output. Remember the repl.start() options? You can set the 'useColors' option to true which will, in turn, instruct the default writer to colorize the output.

Add 'useColors' option when starting repl.

function app() {
 const replServer = repl.start({useColors: true})
}
app()

You can also pass in a function to the writer option to fully customize your output. For instance, to convert your output to uppercase, modify your function as follows.

function app() {
 const replServer = repl.start({writer: modifyOutput})
 function modifyOutput(output){
  return output.toUpperCase()
 }
}
app()

If you try to display a string, the output will be in uppercase.

> msg = ‘Message’
‘MESSAGE’

 

Conclusion

In this article, we discussed what NodeJS REPL is and how you can start the REPL programming environment from the terminal. NodeJS offers a way of working and configuring the REPL from a JavaScript file. This tutorial showed you how you can import and start the repl module. Finally, you learned how to use the NodeJS REPL module inside a function and some of the available configurations. Finally, you saw some examples of how you can use repl.

 

Further Reading

To learn more about the NodeJS REPL module , feel free to visit the documentation.

 

Views: 2

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can reach out to him on his LinkedIn profile or join on Facebook page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment