Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
gwens committed Dec 14, 2016
0 parents commit c2779b5
Show file tree
Hide file tree
Showing 17 changed files with 4,171 additions and 0 deletions.
40 changes: 40 additions & 0 deletions 9781484224410/01-introduction-nodejs.txt
@@ -0,0 +1,40 @@
# Introduction to Node.js

## What's Node.js?

Node.js is a low level and a highly scalable platform, it was created to be explicitly an experiment in asynchronous processing. Using Node.js you will program directly with many network and internet protocols or use libraries that have access to OS resources. To program in Node.js you only need to master JavaScript language – that’s right, only JavaScript! And the JavaScript runtime used in this platform is the famous Javascript V8, which is also used in Google Chrome.

## Main features

### Single-Thread

A single-thread architecture works with only the main thread instance for each initiated process. If you are used to programming in multi-thread architecture, like Java or .NET to use the concurrency processing, unfortunately it won't be possible with Node.js. However, you can works with parallel processing using multiple process.

For example, you can use a native library from Node.js called `clusters` that allows you to implement a network of multiple processes. In Node.js you can create **N-1 processes** to work with parallel processing, while the main process (aka master process) works on balancing the load among the other processes (aka slave process). If your server has multiple cores, applying this technique will optimize the processing's usage.

Another way is to use asynchronous programming, which is one of the main resources from JavaScript. The asynchronous functions on Node.js work as **Non-blocking I/O**, in case your application has to read a huge file it will not block the CPU, because the IO operation runs out of a thread pool, allowing your application to continue to process other tasks requested by other users.

### Event-Loop

Node.js has **event-oriented paradigm**. It follows the same philosophy of event-oriented on JavaScript client-side, the only difference is the type of event, meaning that there are not events such as mouse's `click`, `key up` from the keyboard or any other events from web browsers. In fact, Node.js works with **I/O events**, for example: `connect` from a database, `open` a file or read `data` from a streaming and many others.

![The event-loop process](images/event-loop.png)

The Event-Loop is the responsible agent in noticing and emitting events. Simply speaking, it is an **infinite loop** which in each iteration, it verifies in the event queue if some event was triggered. When an event is triggered, the Event-Loop execute it and send it to the queue of executed events. When an event is running, we can write any business logic on it inside the callback function commonly used in JavaScript.

## Why do I need to learn Node.js?

* **JavaScript everywhere:** Node.js uses JavaScript as a server-side programming language. This feature allows you to cut short your learning process, after all, the language is the same as JavaScript client-side. Your main challenge in this platform is to learn how to works with the asynchronous programming to take most of this technique. Another advantage of working with JavaScript is that you can keep an easy maintenance project – of course, as long as you know who to write codes using JavaScript.
You are going to easily find professionals for your projects and you’re going to spend less time studying a new server-side language. A technical JavaScript advantage in comparison with other back-end languages is that you will no longer use specifical frameworks to parse JSON objects (JavaScript Object Notation); after all, the JSON from the client-side will be same as in the server-side. There are also cases of applications running databases that persists JSON objects, such as the popular NoSQL: MongoDB, CouchDB and Riak. An important detail is that the Node.js uses many functionalities from ECMAScript 6, allowing you write an elegant and robust JavaScript code.

* **Active community:** This is one of the biggest advantages in Node.js. Currently, there are many communities around the world striving to make Node.js a huge platform, either writing posts and tutorials, giving speeches in some events or publishing and maintaining new modules.

* **Active open-source modules:** Today there are +300.000 open-source modules published into NPM which can be used instantly for Node.js projects.

* **Ready to realtime:** Node.js have become popular thanks to some frameworks for realtime communications between client and server. The **SockJS** and **Socket.IO** are good examples. They are compatible with the protocol **WebSockets** and they allow you to traffic data through a single bidirectional connection, treating all data by JavaScript events.

* **Big players:** LinkedIn, Wallmart, Groupon, Microsoft, Netflix, Uber and Paypal are some of the big companies using Node.js and there are many more.

### Conclusion

Up to this point, all the theory was explained: main concepts and advantages about why use Node.js. In the next chapters, we are going to see how it works on practice, with a single condition! Open your mind to the new and read this book with excitement to enjoy this book!
89 changes: 89 additions & 0 deletions 9781484224410/02-setting-up-the-environment.txt
@@ -0,0 +1,89 @@
# Setting up the environment

In this chapter, we are going to install Node.js on the most used OS (Windows, Linux and MacOSX). However, the entire book will use MacOSX as default OS.

Don't worry about the differences among these operation systems, because all examples in this book are compatible with the all the three OS platforms.

## Node.js standard installation

To set up the Node.js environment is quite the same despite the OS. Just few procedures will be different in each OS, especially for Linux, because in Linux environment you can compile an application or install it using a package manager, but it is not a big deal.

![Node.js homepage](images/nodejs-install.jpg)

The first step is to access the official Node.js website: [nodejs.org](http://nodejs.org)

Then, click on the button **v5.6.0 Stable** to download the latest and compatible version for your Windows or MacOSX. If you use Linux, I recommend you to read this quick wiki:

https://github.com/nodejs/node/wiki/Installing-and-Building-Node.js

This wiki explains how to compile and install Node.js in some popular Linux distro.

After the download, install it. If you use Windows or MacOSX, just click in some next, next and next buttons until the installation is completed, after all there is none specific configuration to do it.

To test if everything is running correctly, just open the **Terminal** (for Linux or MacOSX), **Command Prompt** or **Power Shell** (for Windows) type this command:

``` bash
node -v && npm -v
```

This will check the version of Node.js and NPM. This book uses **Node v5.6.0** and **NPM 3.6.0**.

> ##### About io.js and Node.js merge
> Since **September 8th 2015**, Node.js was upgraded from **0.12.x** to **4.0.0** version. This happened because of the merge from **io.js**. The io.js was a fork built and maintained by the Node.js community. They worked to include some features from **ECMAScript 6** implementation, besides making several improvements that were slowly on Node.js. The io.js reached the **3.0.0** version and both groups decided to merge io.js into Node.js, the result was the Node.js **v4.0.0**. This merge not only gave a huge upgrade to this platform, but also gave a more stable and reliable version to Node.js.

**Note:** This book will use the **Node v5.6.0**, with a lot of ES6 codes. To learn more about ECMAScript 6, take a look this website:
http://es6-features.org

## Node.js installation via NVM

**Warning:** This section, we are just going to explore an alternative way to setup the Node.js using a version manager. Feel free to skip this step in case you don't need or don't want to learn how to use the NVM.

Just like Ruby language has the RVM (*Ruby Version Manager*) to manage multiple Ruby versions, Node.js also has a manager too, the NVM (*Node Version Manager*).

NVM is a perfect solution to test your projects in different Node.js versions. It is also useful for people that like to test unstable or latest versions.

NVM has great advantages, it is practical, easy to use, it can uninstall a Node.js version with a single command and will save you time to search and install some Node.js version. It is a good alternative, especially on Linux which its native package managers are frequently outdated and invalidates a new Node.js version to be installed.

### Setup NVM

In few steps you can set up NVM into a MacOSX or Linux system, you just need to run this command:

``` bash
curl https://raw.githubusercontent.com/creationix/nvm/v0.30.2/install.sh | bash
```

Unfortunately, the official version of NVM is not available to Windows, but there are alternative projects created by the community. Here are two similar alternatives for Windows:

* **NVM-Windows:** https://github.com/coreybutler/nvm-windows
* **Nodist:** https://github.com/marcelklehr/nodist

Both have a similar CLI (*Command Line Interface*) inspired by NVM.

### Top NVM commands

As a cake recipe, right bellow I show you a list with the top commands that will be essential to manage multiple versions or at least keep your environment updated with the latest version.

* `nvm ls`: lists all versions installed;
* `nvm ls-remote`: lists all the available Node.js versions to download and install;
* `nvm install vX.X.X`: download and install a version;
* `nvm uninstall vX.X.X`: Uninstall an existing version;
* `nvm use vX.X.X`: choose an existing version to use;
* `nvm alias default vX.X.X`: choose an existing version to be loaded by default in the OS boot time;

**Attention:** change the `vX.X.X` for a Node.js version of your choice, such as `v5.6.0`

### Installing Node.js via NVM

To install Node.js via NVM, you just need to run the following commands:

``` bash
nvm install v5.6.0
nvm use v5.6.0
nvm alias default v5.6.0
```

After running these commands, you will have the Node.js installed and ready to use.

### Conclusion

Congrats! Now, besides having the Node.js installed and working, you also learned a new way to manage multiple Node.js versions via NVM. In the next chapter, we are going to explore some important things about NPM (*Node Package Manager*). So, keep reading, because the fun is just starting!
122 changes: 122 additions & 0 deletions 9781484224410/03-managing-modules-with-npm.txt
@@ -0,0 +1,122 @@
# Managing modules with NPM

## What does NPM do?

Just like RubyGems from Ruby or Maven from Java, Node.js also has a package manager, which is called NPM *(Node Package Manager)*. It has become so popular throughout the community that since the **0.6.X Node.js version** it was integrated within the main Node.js installer, becoming the standard manager of this platform. This helped the developers at that time, because it made several projects converge to this tool.

![npmjs.org](images/site-npm.jpg)

Nowadays, the NPM homepage hosts more than **230k of modules** created by developers, companies and community. **+149 million downloads are made daily and +3.4 million downloads are made monthly**.

## Top NPM commands

Use NPM is very easy to use. You can use it to manage your project's dependencies and you create commands for tasks automation purposes, everything is created and managed into the `package.json` file. See bellow a list of the top npm commands:

* `npm init`: displays a simple wizard to help you create and describe your new project;
* `npm install module_name`: install a module;
* `npm install -g module_name`: install a global module;
* `npm install module_name --save`: install a module and add it into the `package.json` file, inside `dependencies`;
* `npm install module_name --save-dev`: install a module and add it into the `package.json` file, inside `devDependencies`;
* `npm list`: lists all the modules installed on the project;
* `npm list -g`: lists all the global modules installed on the OS;
* `npm remove module_name`: uninstall a module from the project;
* `npm remove -g module_name`: uninstall a global module;
* `npm remove module_name --save`: uninstall a module from the project and also remove it from the attribute `dependencies`;
* `npm remove module_name --save-dev`: uninstall a module from the project and also remove it from the attribute `devDependencies`;
* `npm update module_name`: updates the module version;
* `npm update -g module_name`: updates the a global module version;
* `npm -v`: displays the npm current version;
* `npm adduser username`: creates an account to [npmjs.org](https://npmjs.org);
* `npm whoami`: displays details of your public npm's profile (you must create an account using the previous command);
* `npm publish`: publishes a module into npmjs.org (it's necessary to have an active account first);

## Understanding package.json file

All Node.js projects are called modules. But, what is a module? Throughout the book, note that I am going to use the terms module, library and framework, in practice, they all mean the same thing.

The term **module** was taken from the JavaScript's concept, which is a language that works with a **modular architecture**. When we create a Node.js project, that is, a module, this project is followed by a descriptor file of modules, called `package.json`.

This file is essential to a Node.js project. A `package.json` badly written can cause bugs or even prevent your project to be executed, because this file has some key attributes, that are read by both Node.js and the NPM.

To demonstrate it, see bellow a simple example of a `package.json` that describes the main attributes of a module:

``` json
{
"name": "my-first-node-app",
"description": "My first node app",
"author": "User <user@email.com>",
"version": "1.2.3",
"private": true,
"dependencies": {
"module-1": "1.0.0",
"module-2": "~1.0.0",
"module-3": ">=1.0.0"
},
"devDependencies": {
"module-4": "*"
}
}
```

With those few attributes, you are able to describe about your module. The attribute `name` is the main one. It defines a programmatic name of the project, this module name will be called via `require("my-first-node-app")` function. It must be written in a clean and short way, offering an abstract about what it will be the module.

The `author` attribute is the one which informs the name and email of the author. You can use the format `Name <email>` in order to websites, such as [npmjs.org](https://npmjs.org) can read this information correctly.

Another main attribute is the `version`, it defines the current version of the module. It is highly recommended that you use this attribute to allow a module installation via `npm install my-first-node-app` command. The attribute `private` is optional, it is only a boolean that determines if the project is an open-source or is a private project.

Node.js modules work with **three levels of versioning**.
For example, the version `1.2.3` is divided into the levels:

1. **Major: X.0.0**
2. **Minor: 0.X.0**
3. **Patch: 0.0.X**

Note the **X** means the current level version to update.

In the previous `package.json` have 4 modules, each one uses a different semantic version. The first one, the `"module-1"`, has a fixed version `1.0.0`. Use this kind of version to install dependencies whose updates can break the project if you change the version.

The `"module-2"` already has a certain update flexibility. It uses the character `"~"` which allows you to update a module as a `patch` level `1.0.x` (it only update the `x` version). Generally, these updates are safe, they brings improvements and bug fixes.

The `"module-3"` updates versions which are greater or equal to `1.0.0` in all the version levels. In many cases, using `">="` can be risky, because the dependency can be updated to a `major` or `minor` level and, consequently, can bring some modifications that can break your application.

The last one, the `"module-4"` uses the `"*"` character. This one will always catch the latest version of the module in any version level. It also can cause troubles in the updates and it has the same behavior as the `module-3` versioning. Generally, it is used only in the `devDependencies` which are dependencies used for tests purposes and do not affect the application behavior. **Do not use this kind of version in production environment!**

In case you want to have a more precise control over the versions of your dependencies after their installation in your project, run the `npm shrinkwrap` command. It will lock all dependencies version within the file `npm-shrinkwrap.json` allowing you to have control over the dependencies versions of your project. This command is very used in production's environment, where the versions need to be stricter.

## NPM Task automation

You can also automate tasks using the `npm` command. In practice, you can only create new executable commands running `npm run command_name`. To declare those new commands, just create them inside the attribute `scripts` on `package.json` like this example bellow:

``` json
{
"name": "my-first-node-app",
"description": "My first node app",
"author": "User <user@email.com>",
"version": "1.2.3",
"private": true,
"scripts": {
"start": "node app.js",
"clean": "rm -rf node_modules",
"test": "node test.js"
},
"dependencies": {
"module-1": "1.0.0",
"module-2": "~1.0.0",
"module-3": ">=1.0.0"
},
"devDependencies": {
"module-4": "*"
}
}
```

Note that this new `package.json` created three scripts: `start`, `clean` and `test`. These scripts are executable now via their commands: `npm run start`, `npm run clean` and `npm run test`.
As shortcut, only the `start` and `test` commands can be executed by the alias: `npm start` and `npm test`. Within the scripts, you can run both the commands `node`, `npm` or any other global command from the OS. The `npm run clean` is an example of a global command from the `bash`, which internally runs the command: `rm -rf node_modules` to deletes all files from the `node_modules` folder.

### Conclusion

If you reached this point, you have learned the basics about managing dependencies and automating tasks using npm. It is highly important to understand these concepts, because it will be frequently used throughout this book.

Fasten your seatbelts and get ready! In the next chapter we are going to start our API RESTful pilot project, which is going to be worked on throughout the next chapters. As spoiler, I am going to tell you about what this project will be.

In the next chapters, we are going to create a simple API REST system to manage tasks. Not only an API is going to be developed but also we'll create a web application to consume data from this API. All development is going to happen using some Node.js popular frameworks: Express to create the API resources, Sequelize to persist data in a relational database, Passport to deal with user authentications and a lot more.

0 comments on commit c2779b5

Please sign in to comment.