# Lesson 17 Intro Node.js

# Intro to Nodejs

We have been using JavaScript in the browser, and debugging our JavaScript in Chrome.
What if there was a way to use JavaScript to code, not in the browser but on our desktop like other programming languages, C++, C#, Java?
There is a way to use the JavaScript engine from chrome on the desktop, it is called Nodejs.
Here is it's website: https://nodejs.org/en/

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

We are going to work with the LTS (Long Term Support) version of Nodejs.

# How to Install NodeJS

  • In your browser go to the nodejs page https://nodejs.org/en/
  • Click on the button to download the LTS version of Nodejs.
  • Open the official page for Node.js downloads and download Node.js for Windows by clicking the "Windows Installer" option Run the downloaded Node.js .msi Installer - including accepting the license, selecting the destination, and authenticating for the install.
  • This requires Administrator privileges, and you may need to authenticate.
  • To ensure Node.js has been installed, run this, cmd in your terminal - you should get something a result like v10.15.0

node -v



# What is NPM?

NPM is a package manager for Node.js packages, or modules if you like.
www.npmjs.com hosts thousands of free packages to download and use.

  • Update your version of npm with:

npm install npm --global

  • This requires Administrator privileges, and you may need to authenticate
  • Congratulations - you've now have Node.js installed, and are ready to start using it.

# What is a Package?

A package in Node.js contains all the files you need for a module.
Modules are JavaScript libraries you can include in your project.

# Debugging in NodeJS

In VS Code create a new file named: app.js
here is the code that runs a web server and puts the words 'Hello World' on the page.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

In VS Code you can run and debug the code like you would in Chrome for regular web pages.

  1. To put a code break point in your code, select a code line and press F9 (or click to the left of the line numbers). Choose line 9.
  2. To switch to the Debug panel on the left
  3. To run in debug (Ctrl-Shift-D)
    Debug NodeJS Image
  4. Select "Add Configuration"
  5. Choose Environment Node.js
  6. This will allow you to add a debug environment for Node.js. This will create a launch.json file, save it and close it.
  7. F5 or the little green arrow will run your Node.js application in debug.
    Debug NodeJS Image

You can also run Node.js applications on any command line, without debug. First command is node followed by the file you want to run.

node app.js
Debug NodeJS Image

Now go to your browser and to the local machine address for your server to see the Hello World message.

http://127.0.0.1:3000/

Debug NodeJS Image


# console.log

This command can be used to output to the terminal when running your app from the console/terminal. Prints to the console/terminal with a newline character at the end.

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to the console
console.log('count:', count);
// Prints: count: 5, to stdout

https://nodejs.org/docs/latest-v10.x/api/console.html

If you have an array of objects, the console.table command is valuable.

console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
// ┌─────────┬─────┬─────┐
// │ (index) │  a  │  b  │
// ├─────────┼─────┼─────┤
// │    0    │  1  │ 'Y' │
// │    1    │ 'Z' │  2  │
// └─────────┴─────┴─────┘


# Additional Node.js

# Node.js Modules, What is a Module in Node.js?

Consider modules to be the same as JavaScript libraries.
A set of functions you want to include in your application.

# Built-in Modules

Node.js has a set of built-in modules which you can use without any further installation.
Look at our Built-in Modules Reference for a complete list of modules.

# Include Modules

To include a module, use the require() function with the name of the module:

var http = require('http');
var fs = require('fs');

require is a special command in Node.js that allows a reference to a library.

# Node.js File System Module

The Node.js file system module allows you to work with the file system on your computer.

To include the File System module, use the require() method:

var fs = require('fs');  

Common use for the File System module:

  • Read files
  • Create files
  • Update files
  • Delete files
  • Rename files

# Read Files

The fs.readFile() method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder as Node.js):

HelloWorld.html

<html>

<body>
    <h1>Hello World</h1>
    <p>Web Page Paragraph</p>
</body>

</html>

Create a Node.js file that reads the HTML file, and return the content as a web page.

Example
Serve up a file as a web page.

let http = require('http');
let fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('HelloWorld.html', function (err, data) {
    res.writeHead(200, {
      'Content-Type': 'text/html'
    });
    res.write(data);
    res.end();
  });
}).listen(8080);


# Create Files

The File System module has methods for creating new files:

fs.appendFile() fs.open() fs.writeFile() The fs.appendFile() method appends specified content to a file. If the file does not exist, the file will be created: Here is a link to the Node.js documentation for File System. https://nodejs.org/docs/latest-v10.x/api/fs.html

Example
Create a new file using the appendFile() method.
documentation fs.appendFile(path, data[, options], callback)

let fs = require('fs');

fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
  if (err) throw err;
  console.log('Saved!');
});

appendFile has three required parameters:

  • path: string, filename, URL
  • data: string, content we want to add to our file
  • callback function, a code function to handle the completion of saving.

The fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a new file, containing the specified content, will be created:

Example Create a new file using the writeFile() method: This will overwrite the file if it already exists.

let fs = require('fs');

fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {
    if (err) throw err;
    console.log('Saved!');
});


# Passing in arguments to your Node.js app on the command line

process.argv is an array of strings.
For the Node.js documentation look at https://nodejs.org/docs/latest-v10.x/api/process.html#process_process_argv

  • create a new file - test.js
// print process.argv 
process.argv.forEach((val, index) => {
    console.log(`${index}: ${val}`);
});

Call the new file test.js with 2 arguments.

> node test.js "Pass in a string" 3

0: C:\Program Files\nodejs\node.exe
1: C:\Users\mhard\src\mhintegrity\lesson17\names
2: Pass in a string
3: 3

Now try calling the app with some arguments.
Side Note: What is the difference between and argument and a parameter.

A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters.

function test(myParameter) {
    console.log(myParameter);
}
let myArgument = "What I am passing is my argument";
test(myArgument);



# Assignment due for discussion next class and checked into GitHub by the Monday after that.

  1. Write an app randomName.js, Use fs from this lesson and JavaScript from Lesson 15 to create console output with a Random Full Name in it.
  • Create two arrays, one first names and the second last names. Then randomly put them together in a string and output to the console.
  • Here is an example of running the app and output:
> node randomName
> Fred Flintstone
  1. Create a second app namesFile.js.
  • save a list of 10 random names out to a file named Names.txt
  1. Create another app named names.js.
  • accept 2 arguments, fileName and Number
  • output a number of random names to a file with the .txt extension
  • optionally, if the file name is console, output to the console instead.
    example:

node Names "middleEarth" 5



Link to Debugging in VSCode


# Next Lesson

Lesson 18 Intro Vue.js