Intro to Node.js (Part 1)
Tags: node, codenewbie, javascript, intro
Published: 2020-12-21 03:20:49

It's time to start learning [Node.js](https://nodejs.org/en/)!  I'll share what I'm learning with the help of the amazing [Net Ninja's tutorial](https://www.youtube.com/playlist?list=PL4cUxeGkcC9gcy9lrvMJ75z9maRw4byYp) on this topic.

## What is Node.js?

Node.js is an open-source platform that runs JavaScript on a computer or server outside of the web browser.  It allows for easy communication with the database with functionalities for reading, deleting and updating files. 

Node.js is itself written in C++, but as a program it allows us to write in JavaScript. It runs fast thanks to the embedded V8 engine (an engine which takes JavaScript and converts it to machine code for the computer to run).

It also comes with a ton of open source packages - npm (Node Package Manager). 

## Installation and Usage

Node.js can be downloaded from their website: https://nodejs.org/en/. 

You have the option of downloading the latest stable version or the latest version with more features but unstable. 

To check if you have it installed, run the following in the terminal:

```
$ node -v
```

This will give you the version of Node.js that's installed in your device, assuming it's there. 

Everything in Node is run through the terminal.  In order to run a file in Node, first be sure that you're in the directory of that specific file, and in the terminal run `node` followed by the name of the file:

```
$ node nameOfFile.js
```

## Global Objects

Node.js global objects are available in all modules (which are JavaScript files), which gives us access to various methods.  

For those of us who use JavaScript, these global functions should look familiar: 

`console.log()`
`setTimeout()`
`setInterval()`
`clearTimeout()`

Some global objects include:

`__dirname`
*This tells us what directory we are in.*

`__filename`
*This gives us the file name as well as the directory it's in.*

## Function Expressions

A common pattern in Node.js is function expressions written in the following way:

```javascript
const greeting = function() {
  console.log('Greetings, Earthlings.');
};
greeting();
```

## Modules and How to Use Them

In Node.js, we split code into logical modules - which are simply JavaScript files - and then call upon those modules when we need them.  This helps with organization and results in code that is easier to understand and debug. 

Let's create a module called `greeting` that accepts a parameter for a name to include in the greeting message.  You'll notice that at the bottom we are exporting this module.  We need to do this in order for other files to be able to use this module: 

**greeting.js**
```javascript
//  Here we write the function of this model:
const greeting = function(name) {
  return `Greetings, ${name}!`
}

// This export line must be included in order to make it available for use in other files
module.exports = greeting;
```

Now, let's say we want to use the `greeting` module in the main `app.js` file.  we'll first need to require the module that is going to be used and assign it to a variable so that we can utilize its function: 

**app.js**
```javascript
const greeting = require('./greeting');

console.log(greeting('Goku'));
```

### Multiple Functions in a Module

When a module has multiple functions, the export line at the bottom is what looks a little different. 

Let's go back to our original module and add another function to it:

**greeting.js**
```javascript
const greeting = function(name) {
  return `Greetings, ${name}!`
}

const casualGreeting = function(name) {
  return 'What's up, ${name}!'
}

// The greeting property of the exports object is equal to the function
module.exports.greeting = greeting;
module.exports.casualGreeting = casualGreeting;
```

Again, we just need to require the module inside of the file that we want to use, and in this way we export multiple functions from one module. 

Alternatively, the same thing can be done by writing the module as follows:

**greeting.js**
```javascript
module.exports.greeting = function(name) {
  return `Greetings, ${name}!`
}

module.exports.casualGreeting = function(name) {
  return 'What's up, ${name}!'
}
```

Here is a third way to write the module performing the exact same functionalities: 

**greeting.js**
```javascript
const greeting = function(name) {
  return `Greetings, ${name}!`
}

const casualGreeting = function(name) {
  return 'What's up, ${name}!'
}

// We are creating an exports object
module.exports = {
  greeting: greeting,
  casualGreeting: casualGreeting
};
```

## Built-In Modules

There are several built-in core modules that can be required the same way custom modules are required. 

### Events Module

One such module is the Events module, which allows us to create, invoke and listen for custom events we create. 

**battleMode.js**
```javascript
// First, we require the Events module and assign it to a variable.  Node recognizes the module name because it is already built in.
const events = require('events');

// Now we can create an EventEmitter object:
const emitEvent = new events.EventEmitter();

// Create a function that will be executed when the event we created is fired:
emitEvent.on('threatened', function(fight) {
  console.log(fight);
});

// Here we are firing the event and passing in the function that is to be executed: 
myEmitter.emit('threatened', 'Ka~me~ha~me~HAAAAA!!!');
```

### File System Module

Another core built-in module is the File System module, which allows us to interact with with the file system on our computers.  For example, we can read and write files by utilizing this module: 

**app.js**
```javascript
// As always, we are requiring the module at the top:
const fs = require('fs');

// Synchronous method for reading:
const readThis = fs.readFileSync('readThis.text', 'utf8');
  // The first parameter takes the name of the file we want to read
  // The second parameter is the character encoding so that the computer understands the JavaScript code being run

// Synchronous method for writing:
fs.writeFileSync('writeThis.txt', 'readThis');
  // The first parameter takes the file that we want to write to
  // The second parameter takes the data we want written to that file
  // If the file we are writing to does not yet exist, this line of code will create it

// Asynchronous method for reading:
fs.readFile('readThis.text', 'utf8', function(err, data) {
  fs.writeThis('writeThis.txt', data);
});
  // The first parameter takes the file we want to read
  // The second parameter is the character encoding
  // The third parameter is the callback function to fire when the process is complete
    // The callback function takes two parameters:
    // 1) Error if there is a problem with the method
    // 2) The data we are retrieving
```

If we want to delete a file, simply run:

```javascript
fs.unlink('fileToBeDeleted.txt')
```

We can also create and remove directories with this module. 

**app.js**
```javascript
// You probably get it by now that we need to require the module first
const fs = require('fs');

// Synchronously create and remove directories:
fs.mkdirSync('someDirectory');
  // Pass in the directory name we want to create

fs.rmdirSync('someDirectory');
  // Pass in the directory we want to delete

// Asynchronously create and remove directories:
fs.mkdir('someDirectory', function(){
  fs.readFile('readThis.txt', 'utf8', function(err, data){
    fs.writeThis('./someDirectory/writeThis.txt', data);
  })
});
  // Since this is asynchronous, it takes a callback function where we read and write the file inside the newly created directory

fs.unlink('./someDirectory/writeThis.txt', function(){
  fs.rmdir('someDirectory');
});
  // Again, this is asynchronous so it takes a callback function that deletes the directory
  // In order to delete a directory, it must be empty, so we would first need to remove any file inside of it
```

I hope this helps.  I'm looking forward to learning more about Node.js! 

## Helpful Links

- [The Net Ninja's Node.js Tutorial](https://www.youtube.com/playlist?list=PL4cUxeGkcC9gcy9lrvMJ75z9maRw4byYp)
- [Node.js Global Objects](https://www.tutorialspoint.com/nodejs/nodejs_global_objects.htm#:~:text=Advertisements-,Node.,object%20itself%20as%20explained%20below.)