Node JS Crash Course 2021
Tags: node, javascript, webdev, letsbuild
Published: 2021-06-13 07:49:05

##### pre requisite: you should know JavaScript.  

#What is Node?
Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project!

Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows Node.js to be very performant.

#How Node work?

A Node.js app runs in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.

When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.

This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.

#Why you should learn Node?
Node.js has a unique advantage because millions of frontend developers that write JavaScript for the browser are now able to write the server-side code in addition to the client-side code without the need to learn a completely different language.

#Example of Node use cases
From writing/reading from a file to creating a web server to connecting to the DB to programming a robot with Johnny-Five: The JavaScript Robotics & IoT Platform. "Sky is the limit"

#How to install Node JS
Node.js can be installed in different ways. This post highlights the most common and convenient ones.

Official packages for all the major platforms are available at https://nodejs.org/en/download/.

One very convenient way to install Node.js is through a package manager. In this case, every operating system has its own.

On macOS, Homebrew is the de-facto standard, and - once installed - allows you to install Node.js very easily, by running this command in the CLI:

```
brew install node
```

The best way to install Node JS in my opinion from their website. 
https://nodejs.org/en/

#How to Run Node?

So far we know how to run JS in the browser dev tools. In the case of Node our terminal will be our dev tools(kind of). 

So we will create a folder called "node-js" - you can call your folder whatever you like.

I am in windows 10 and using windows terminal, I can right click the folder and chose "open in Windows terminal". If you are in a different OS or don't have Windows Terminal, you can use 'mac terminal' for mac and 'command prompt' for windows.

once my terminal opens in the folder "node-js", I can write <code>code .</code> to open up my VS code in the same folder.

<em>Note: if you prefer, you can also use the vs code terminal by clicking 'Terminal' and then 'New Terminal'</em>

We are going to create a file "index.js". In this file we will write-
```JavaScript
console.log("Hello World")
```
Now, in order to run this 'index.js' file, we will go to the terminal and make sure we are still in the same directory that contains the index file and simply type in the terminal:
```JavaScript
node index.js
```
we should see the result:

![hello world](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vzclhol5ni6klejw4kxb.png)

<em>Congratulation! you just wrote your first node js app</em>

#What is Global Object?

In the browser, most of the time what we are doing is interacting with the DOM, or other Web Platform APIs like Cookies. Those do not exist in Node.js. We don't have the <code>document</code> or <code>window</code> and all the other objects that are provided by the browser.

However, Node.js provides nice API's through its modules, like the filesystem access functionality.

Node.js also has a global object called 'global'. So if we <code>console.log(global)</code> we get:
![global object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lmhuuzduerzly4eurq3.png)

#node module and NPM

When we installed Node in our system, it came with NPM. NPM stands for Node Package Manager. Through NPM we can install node modules and also a lot of third party packages in our own program.

First, lets create a package.json file. A package.json file is simply a json object that holds all the dependency, scripts, version and a whole lot more for the project you are working on. You can think of this as the 'settings' for your project. Let's create the file with this command in the terminal.
```
npm init -y

```
<code>-y</code> is the flag that tells NPM yes for all the questions rather that answering it one by one. 

Second, lets talk about module. Node.js uses by default what they call "CommonJS module system". So in order to get a module in our 'index.js', lets say  the 'fs' module, we have to do this-
```javaScript
const fs = require('fs');
```
In the above example, we are creating a variable 'fs' and assigning the 'fs module' with the require syntax.

#How to use ES6 import/export in Node?
There are two ways to have ES6 syntax with Node.js modules. First we can just change our 'js' extension to 'mjs' extension for all of our files. mjs stands for module js in node which is opposite of cjs which is the default common js.

Second way to have ES6 import/export is to include <code>"type" : "module"</code> in our package.json file.

```javaScript
{
  "name": "node-js",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "LetsBuild",
  "license": "ISC",
  "type": "module"
}
``` 

#The Node.js fs module
The fs module provides a lot of very useful functionality to access and interact with the file system.

There is no need to install it. Being part of the Node.js core, it can be used by simply requiring it:

```JavaScript
const fs = require('fs')
```
We can use the fs module to read from a file. Lets create a text file call 'hello.txt'. In this file lets put a string Hello World, it does not have to be in quote.

We are going to read from this file and then console.log it.
here is the code:
```javaScript
fs.readFile('hello.txt', 'utf8', (error, data) => {
  if(error) {console.error(error)}
  else {console.log(data)}
})
 ```
result: <code>Hello World</code>

In the above code we are first mentioning which file to read from, then utf8 encoding and then it takes a call back function.

Lets try to add some more text in that file.
```javaScript
const data = ' Like and Share'
fs.appendFile('hello.txt', data, (error) => {
    if(error) {console.error(error)} 
    else { console.log('Data added')}
})
```
result: <code>Hello World Like and Share</code>

Now with similar approach we can also create a file from scratch.
here is the code:

```javaScript
const data = 'Please subscribe!'
fs.writeFile('subscribe.txt', data, (error) => {
    if(error) {console.error(error)} 
    else { console.log('file created')}
})
```
result: subscribe.txt file has been created with the 'Please subscribe!' text in it.

At last to delete we have to mention the file name to delete and handle if there is any error.

```javaScript
fs.unlink('hello.txt', (error) => {
    if(error) {console.error(error)} 
    else { console.log('file deleted')}
})
```
To learn more about Node, check out the full tutorial here:
https://www.youtube.com/watch?v=3QRrXjnGM70

{% youtube 3QRrXjnGM70 %}