14.4. Now the Basic Node.js Steps

14.4.1. First

In an empty directory

Example 14.2. Write a JavaScript file: ~/nodeMyGPNode/js0.js
'use strict';
let marr = ["abc", "def", "ghi"];

let printNumbers = function (arr) {
    for (let elm of marr)
        console.log(elm);
}

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 14.3. Now, You May Test Interactively

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.

qux ~  $ node
Welcome to Node.js v15.6.0.
Type ".help" for more information.
> console.log('hello, World!');
hello, World!
undefined
> let arr = ['abc' 'def', 'ghi'];
undefined
> for (let elm of arr)
... console.log(elm);
abc
def
ghi
undefined
>
(To exit, press Ctrl+C again or Ctrl+D or type .exit)
>
qux ~  $

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

It is probably easier to work with an editor to create js files, and then testing them with node.


14.4.2. But You may Also

Write a JavaScript file

Example 14.4. messages.js
"use strict";
let messages = [
    "A program 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 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 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.