Now the Basic Node.js Steps

First

In an empty directory

Example 15.3. Write a JavaScript file: js0.js
let marr = ["abc", "def", "ghi"];

let printNumbers = function (arr) {
    arr.forEach(function(num) {
        console.log(num);
    });
}

printNumbers(marr);

When the file is saved in your project folder. You issue the following command on the CLI:

node js0

or

node js0.js

resulting in

$ node js0
abc
def
ghi
$

Example 15.4. Now, Let's Do It Differently

You have seen previously on this channel that in the browser you may do some JavaScript coding on the console. In Node.js we have access to a command line interactive interface by just keying in node, and pressing return.

$ node
Welcome to Node.js v13.3.0.
Type ".help" for more information.
> let printNumbers = arr => {
... arr.forEach(num => console.log(num));
... };
undefined
> printNumbers(["a","b","c"]);
a
b
c
undefined
>

Example 15.5. or, equivalently, but more readable
$ node
Welcome to Node.js v13.3.0.
Type ".help" for more information.
> let printNumbers = function (arr) {
... arr.forEach(function (num) {
..... console.log(num);
..... });
... }
undefined
> printNumbers(["abc", "def", "ghi"]);
abc
def
ghi
undefined
>

The node interpreter is exited by .exit, Ctrl-d, or Ctrl-c Ctrl-c.


Then

Write a JavaScript file

Example 15.6. messages.js
"use strict";
let messages = [
    "A program or two a day makes the doc go away.",
    "You can do it!"
    "Yes you can!"
];

then start node and do the following

$ node 
Welcome to Node.js v13.3.0.
Type ".help" for more information.
> .load messages.js
"use strict";
let messages = [
    "A program or two a day makes the doc go away.",
        "You can do it!",
            "Yes you can!"
            ];
            
'use strict'
> messages.forEach(function (message) {
... console.log(message);
... });
A program or two a day makes the doc go away.
You can do it!
Yes you can!
undefined

The .load command loads a prepared file as if you have just keyed it in.

Now type .save positiveMessages.js, and then exit the interpreter. Verify the content of the saved file. This means that experiments may be saved into regular codefiles as if they came from anb editor.