There are three main ways to launch Node code:
To start Node REPL, run the following command in your terminal:
$ node > 1+1 2 > "Hello"+" "+"World" 'Hello World'
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.
This is the most common option because we can save extended Node programs and run them.
To run a file through Node, type
For example, to launch code from a program.js file which is located in a current folder, run:
We don’t need to add the
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:
This code is equivalent to
node index.js node index