In an empty directory
~/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 $
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.
Write a JavaScript file
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.