Launch Node.js

Launching Node.js Scripts

There are three main way to launch Node code:

  • REPL
  • Eval option
  • Running file 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
2
> "Hello"+" "+"World"
'Hello World'

2. Eval Option

If all we need is a quick set of statements, there’s a 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 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, OS information or run any Node code such as working with a file system, database or HTTP.

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

3. Running file through Node

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

To run a file through Node, simply 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 that we’re going to run a javascript file.

If you need to execute code from a file which is in a different folder, just 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