Highway to Shell, with NodeJS

If we execute node without arguments from the command line, we obtain a REPL (Read-Eval-Print-Loop) environment. Inside this

If we execute node without arguments from the command line, we obtain a REPL (Read-Eval-Print-Loop) environment. Inside this ‘shell’ we can write a javascript code that will be executed immediately; this is very useful to experiment with NodeJS, to debug and to learn javascript.

Your own REPL

The REPL interface in NodeJS is a module that we can use to create our own REPL envieronments inside our applications. This enables us to communicate with our application while it is being executed.
In order to add REPL functionality to our application, we should use repl.start from the repl module:

Then, by executing the application we have a REPL environment with our personalized prompt:

In addition to indicating the prompt, we can pass an object to the function repl.start, with the following fields (among others):

  • prompt– The prompt, as we have seen.
  • input– Input Stream. It is process.stdin, by default.
  • output– Output Stream. It is process.stdout, by default.
  • eval– A function that will be used to assess each input stream. It is an eval() wrapper by default. At the end I will show how to make a personalized assessment.

REPL Context

The repl runs on its own context. Therefore, if we want to have access to data outside this context we can assign new properties to the context object of the REPLServer in the following way:

In this case, we are adding the object obj and the function printObj to the repl context. Then, executing the application:


We can see that, from the repl, we have access to the object and the function. Moreover, if we modify the properties of the object from the repl, they are modified in the context of the application as well.

Connection through TCP socket

Using the net module of nodejs we can set a repl interface in a TCP socket, and then get connected to the socket remotely by means of a client (for example, netcat). We can do that in the following way:

Then, we can get connected with netcat:

Personalized assessment function

As we have seen, we can use our own assessment function, which should have the following form:

For example, an assessment function that shows the input using only capital letters:

Please note that we replace the end of the line since the cmd includes it. Then, we execute the application and we obtain the expected result:

For more information

-Oficial reference: https://goo.gl/gG3jNi
-Build Your Own App Specific REPL For Your NodeJS App: http://goo.gl/lc0tTN
-Simple Telnet Server in Node.js: http://goo.gl/vbkPDK

Share this articleShare on LinkedInTweet about this on TwitterShare on FacebookShare on Google+Email this to someone
Go Back