Node by example: 11. REPL
Published on April 29, 2010
0 Comments
11. REPL
The complete source code can be downloaded here: http://github.com/Hendrik/node-by-example
A Read-Eval-Print-Loop is available both as a standalone program and easily includable in other programs. REPL provides a way to interactively run JavaScript and see the results. It can be used for debugging, testing, or just trying things out.
Start a REPL via:
repl.start(prompt, stream)
where "prompt" is optional and defaults to "node> "
"stream" is options as well and defaults to process.openStdin().
Inside the REPL, Control+D will exit.
The following example will start a tcp server listening to port 8000 and we will use the REPL to check & modify the available variables:
See 12_repl/repl.js:
var sys = require("sys"),
net = require("net"),
repl = require("repl");
no_connections = 0;
some_var = "Hello";
net.createServer(function(socket) {
sys.puts("Connection!");
no_connections += 1;
socket.end();
}).listen(8000);
repl.start("repl.js prompt> ");
First make sure to include the repl module:
var repl = require("repl");
Next we set 2 variables, which we will manipulate through the REPL:
no_connections = 0; some_var = "Hello";
Any client connecting to the tcp server will increase the "no_connections" variable:
net.createServer(function(socket) {
sys.puts("Connection!");
no_connections += 1;
socket.end();
}).listen(8000);
Start the example via:
node repl.js
You will notice that instead of a running process you are presented with a prompt:
# node repl.js repl.js prompt>
Enter the following to get the value of the no_connections variable:
repl.js prompt> no_connections
Increase it one or more times and check again:
repl.js prompt> ++no_connections
As you can see the REPL is very useful for debugging and testing your node scripts.
