Previously we saw what NodeJS is and what all we can do with it. That all is fine but HOW DO I WRITE CODE on NodeJS?????
Whenever you start learning a new language it is customary to write a Hello World Application. It is the rule. So here we write the code for Hello World Application which will display “Hello World” in the output.
First of all create a new folder/directory where you will store all your code. Yes!! you need a separate folder for each. Why?? It will be explained with package managers.
In this file, we first define a new function sayHello() which will print Hello World to the console.
We print text to the console using console. Console refers to the terminal using which you will execute this script.
After defining the function, we need to call the function. We call the function just like in any other language.
Now to run this script, open the terminal at the location of this file and start the script using
$ node server.js
You should see an output like:
That is it. Your first application just ran successfully.
REPL stands for Read Eval Print Loop. To start this terminal, enter the following in the terminal.
This terminal can evaluate various expressions ranging from simple addition to very complex array operations.
The REPL terminal also supports multi line expressions like those used in for loop, if else etc. It looks for open braces and automatically checks for the termination of the bracket. Multiline expressions are automatically prepended with ‘…’ as shown in the following example.
REPL terminal also stores the previous result in a special variable _ .
The “undefined” being displayed after some functions is the return value of the function. Since console.log() only prints the value to console but does not return any value, hence the result is undefined.
There are some REPL terminal specific commands also which you can use:
Exits the current function or line
Ctrl+C twice or .exit
Exits from the REPL terminal
Alias for .exit
Break from multiline expression
Opens up editor in terminal (like vim or nano) to write scripts
This is about the inbuilt Node REPL terminal. Node provides a functionality to design your own REPL terminal but this is beyond the scope of this article.