Over a million developers have joined DZone.

Execute code each time the Node.js REPL starts

DZone's Guide to

Execute code each time the Node.js REPL starts

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

If you start the Node.js binary without any arguments, you are in the REPL (Read-Eval-Print-Loop), a JavaScript command line. This post shows you how to execute code each time the REPL starts. That allows you to, say, automatically load modules you want to use.

I have not found a way to perform the code execution via a configuration file, but you can make it happen via the following trick: Write a script that executes the code and then programmatically starts a REPL. Example: The following are the contents of a file called startnode.js.


    var repl = require("repl");
    var context = repl.start("$ ").context;
    // Configure what’s available in the REPL
    context.util = require("util");
Under Unix, the first line lets you run startnode.js as a command, if you make it executable.
    rauschma> chmod u+x startnode.js 
    rauschma> ./startnode.js
    $ util.log("hello")
    17 Nov 21:39:29 - hello
You can also use the following command to run it (with or without the first line):
    rauschma> node startnode.js
The Node.js documentation has more information on the REPL API and on commands that are available while running it. For example:
    $ .help
    .break Sometimes you get stuck, this gets you out
    .clear Break, and also clear the local context
    .exit Exit the repl
    .help Show repl options


From http://www.2ality.com/2011/11/node-repl-start.html

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}