Launch Node.js

Launching Node.js Scripts

There are three main ways to launch Node code:

  • REPL
  • Eval option
  • Running files through Node

1. Node.js Console (REPL)

Node.js has a virtual environment called Read-Evaluate-Print Loop (REPL). Using REPL (Node console), we can execute Node.js/JavaScript code.

To start Node REPL, run the following command in your terminal:

$ node

For example

$ node
> 1+1
> "Hello"+" "+"World"
'Hello World'

2. Eval Option

If all we need is a quick set of statements, there’s an eval -e option that allows us to run inline JavaScript/Node.js.

For example, to print the current date, run this in your Terminal / Command Prompt:

node -e "console.log(new Date())"

Another example prints the Node version:

node -e "console.log(process.versions.node)"

Node eval (-e flag) is useful in npm and bash scripts because it allows you to execute Node in a very compact manner in the bash, zsh, or any other shell environment without having to have a Node file.

We can get versions and OS information or run any Node code, such as working with a file system, database, or HTTP.

However, don’t use this option if you need to write a long code.

3. Running files through Node

This is the most common option because we can save extended Node programs and run them.

To run a file through Node, type node filename.

For example, to launch code from a program.js file which is located in a current folder, run:

node program

We don’t need to add the .js extension because it knows we will run a javascript file.

If you need to execute code from a file that is in a different folder, provide the relative or absolute path:

node ./app/server.js
node /var/code/app/server.js

If we have index.js in a folder, we can execute with a dot:

For example:

node .

This code is equivalent to

node index.js
node index