Node comes with a command-line tool node
to help you run JavaScript programs from your terminal.
There are two main ways to use it - by giving it a file to run, or by using the REPL
Imagine you have a file called hello.js
.
In that file, you have some simple JavaScript code:
To execute this code on your computer, you can pass the file to the node
executable:
This should result in the words "Hello, world" appearing in your terminal. Congratulations.
Using this, you can run entire applications and websites, whatever you want to build, from your terminal.
REPL stands for Read-Eval-Print-Loop. Any self respecting programming language/framework/runtime ships with one, and Node is no different.
What does this mean though?
Basically, you can write code in and see the output straight away. This makes it really useful to use as a sandbox/playground type thing for quickly trying things out and experimenting.
To open the Node REPL, you can just use the node
executable on it's own, and you should then see on a new line a >
character followed by a slightly indented cursor. If so, that's it, you're in!
You can now just write JavaScript like you were writing it into a file:
So if you ever need to try out an idea, or test how a function works for example, this is the place to do it.
N.B. In the above example, where we defined the add
function:
There are three dots at the start of the lines - this indicates that you have an unterminated block in your code (in this case, the function body, where we have the opening braces but no accompanying closing brace. Every time you open a new block, you'll get some more dots. The code won't evaluate until the block is closed.