--- tags: ironhack, lecture, --- <style> .markdown-body img[src$=".png"] {background-color:transparent;} .alert-info.lecture, .alert-success.lecture, .alert-warning.lecture, .alert-danger.lecture { box-shadow:0 0 0 .5em rgba(64, 96, 85, 0.4); margin-top:20px;margin-bottom:20px; position:relative; ddisplay:none; } .alert-info.lecture:before, .alert-success.lecture:before, .alert-warning.lecture:before, .alert-danger.lecture:before { content:"đŸ‘šâ€đŸ«\A"; white-space:pre-line; display:block;margin-bottom:.5em; /*position:absolute; right:0; top:0; margin:3px;margin-right:7px;*/ } b { --color:yellow; font-weight:500; background:var(--color); box-shadow:0 0 0 .35em var(--color),0 0 0 .35em; } .skip { opacity:.4; } </style> ![logo_ironhack_blue 7](https://user-images.githubusercontent.com/23629340/40541063-a07a0a8a-601a-11e8-91b5-2f13e4e6b441.png) # Node | Intro & Installation ## Learning Goals After this lesson, you will know: - what a *runtime* is on a high-level, - what Node.js is, a bit of its history, and why you would use it, - how to use Node.js on your computer, - what packages/modules are, and their benefits and - how to use *npm*, which stands for Node Package Manager. ## What is Node.js? :::info lecture Node.js intro ::: Node.js (sometimes called just _Node_ for short) is a JavaScript **runtime** developed by Ryan Dahl. Dahl created Node because of the [synchronous limitations of current web frameworks](https://www.infoq.com/interviews/node-ryan-dahl). **Node has allowed us to run JavaScript anywhere, including web servers** (and robots). In the past, the only runtime environment for JavaScript was the <b>browser</b>. Chrome, Safari, and Internet Explorer had their JavaScript runtimes, but we *could not* run JavaScript on our computers. Dahl changed this by extracting the open source <b>[`V8`](https://en.wikipedia.org/wiki/Chrome_V8)</b> runtime environment from Chrome and creating an implementation for servers. :::info :eyes: To summarize, before Node, the only place where you could use JavaScript was a client-side environment - the browsers. Thanks to Node, we can **use JS in the backend** side as well (aka, the server side) and this makes us, as JavaScript developers, full-stack developers. So thanks Node. ❀ ::: :::info lecture C'est grĂące Ă  Node qu'un dĂ©veloppeur JS peut maintenant devenir fullstack ! ::: ### Runtime Environment :::info lecture Node.js est un interpreteur qui va traduire le code JS Ă©crit en code Ă©xĂ©cutable par la machine. ::: A **runtime environment** is an environment which includes all of the tools and features needed to run a specific program, or in the case of Node.js, a programming language. Your computer is dumb. It only understands machine language, 1s, and 0s. Your computer doesn't understand JavaScript, Python, Ruby, Java and most other languages. These languages have to be translated into [bytecode](https://en.wikipedia.org/wiki/Bytecode), which is then turned into machine code and read by the host operating system, or an interpreter, all while taking into account things like [memory management](https://en.wikipedia.org/wiki/Memory_management), accessing the file system, or using native operating system features. :::warning :astonished: These terms can sound overwhelming, but take it slow! If you're interested in knowing more about **how computers process programming languages**, try to find some answers on Google. Fully understanding these concepts is not the main focus of this course but we are sure down the road, you'll pick it up. ::: So this is what **Node.js** does actually - it **translates a JavaScript program into bytecode** for a computer to run it. This topic is enough to teach a class on, and out of scope for this lesson, but in short, JavaScript previously was only able to be run in the browser. Node.js allows us to run it anywhere! :::info lecture Un des gros avantages de Node est que l'on va pouvoir exĂ©cuter un meme code javascript : que cela soit cĂŽtĂ© client ou cĂŽtĂ© serveur. ::: ### What Node.js is *not* :::info lecture ☝ Node.js n'est ni un langage, ni un framework. ::: The following are common misnomers and misconceptions related to Node: - It is ***not*** a framework (there are frameworks built on top of Node.js though). - It is ***not*** a programming language (the language is still JavaScript). ## Why Node.js? :::info lecture PROs ::: Because Node uses JavaScript's *event-driven* and <b>*asynchronous*</b> model, it excels with certain web applications such as chat applications, and apps that need real-time, live updating features. Another (subjective and debatable) benefit is the language of JavaScript <b>being universal</b>. Related to that is the concept of sharing code between frontend and backend since both use JavaScript. Sometimes this can be questioned as well since the backend code is very different, even if it is the same language. Also, Node has a <b>strong and growing ecosystem</b>. This includes packages created by the community and continuing open source development on the runtime itself. Because Node uses [Google's V8](https://developers.google.com/v8/) behind the scenes, Node also benefits from competition between browsers. As <b>Google improves V8</b> to compete with [Mozilla's SpiderMonkey](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey), [Microsoft's Chakra](https://github.com/Microsoft/ChakraCore) and others, Node reaps the benefits of those improvements as well. ## Installing Node :::info lecture VĂ©rifions que tout le monde dispose de `node` et `nvm` : ::: Installing Node is relatively easy. We can use `brew` or `apt-get` to install Node on Mac or Linux, but we're also going to want to keep Node up to date. Some projects may use a different version of Node than your own. This can become a hassle to deal with, so what we would suggest doing is installing [Node Version Manager(nvm)](https://github.com/creationix/nvm). :::info Another great alternative is [n](https://www.npmjs.com/package/n). ::: **NVM allows you to pick which version of Node to use, install new versions, and more**. ### Installing NVM First, we have to install some prerequisites. #### Mac In the terminal: ``` $ xcode-select --install ``` #### Ubuntu In the terminal: ``` $ apt-get update $ apt-get install build-essential libssl-dev ``` Then, we can install NVM. ``` $ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash ``` Test to see if it is correctly installed with: ``` $ nvm --version 0.32.1 ``` At the time of writing, the most recent stable version of Node is 10.15.3. Let's install and use this with NVM: ``` $ nvm install 10.15.3 ``` To update your terminal settings, run the following: ``` $ nvm use 10.15.3 ``` Now test to make sure the installation is complete: ``` node --version ``` ## Our Usage of Node In this course, we will use Node at first to learn some new features of JavaScript, and write some more complex JavaScript algorithms. Later on, we will use Node as a web server (we will be talking about servers soon), and a web framework built on top of Node - Express. ## Our First Code :::info lecture Notre premier programme, `test.js` : ::: Create a new file in your code directory called `test.js`. In this file, add the following code: ```javascript console.log("Hello Node"); ``` In your **terminal**: ``` $ node test.js Hello Node ``` We can write any JavaScript code we like in Node, but we must keep in mind *there's no DOM*. So that's it! We're up and running with Node. ## npm and modules :::info lecture NPM intro ::: ### Intro :::success **npm** is a package manager for Node. This means that you and other coders can share your JavaScript code easily, using a command line tool. ::: npm has one of the most robust ecosystems for external packages. At the time of writing, there are over 35,000 npm modules available for you to download! :::info A **package** or **module** is a bundle of reusable code that is packaged with the code it depends on (and that code is called *dependencies*). ::: The benefits of modules are endless, and we will discuss them shortly. ### What is a package manager, and why? #### Packages for your projects are hard to manage When working on your code amongst a team, it's *really* tricky to keep all the versions and dependencies aligned amongst everyone. Let's say you and Bob work on a project together. Bob is using version `1.2` of some module. You're using version `1.8`. The problem here is that the code between those two versions may have changed drastically. You and Bob go to implement a new feature using this package, and now your version works on your computer, but not on Bob's. Now imagine there are 100 other Bobs on your team. When that package updates, everyone has to update their version, or they're running into problems. ![](https://media.giphy.com/media/As8upVH7z3vkQ/giphy.gif) This is a nightmare! However, package managers can come to your rescue! We will get to how npm solves this problem shortly. :::success NPM encourages good software development principles and code sharing. ::: Let's say you, as Mr./Mrs. Junior software developer, go to work at Megacorp Software after you graduate from Ironhack. On your first day, your senior developer sits you down and asks you to help build their shopping cart feature. They ask you to write the business logic for calculating shipping prices and tax for their new sports section. You sit around for hours, researching logistics, shipping companies, and the tax rates for hundreds of cities around the world. This is when you realize, "Hey, this functionality already exists somewhere. We've done *all* of this in the shopping cart for our clothing section." You, as the pro software developer (which you are), copy and paste *allllll* of the code for the clothing shopping cart to the sports shopping cart, making heavy use of your find and replace feature. The next day, Mr(s). Senior developer asks you to build out *another* shopping cart, this time for food goods. Copy and paste the code again? No! All of this functionality could be extracted into modules and shared across your codebase. The logic for calculating tax, logistics, shipping, all could be separate modules that everyone in the company shares! *Not only is extracting code into modules a timesaver for you, but it also is a useful software development practice and saves the company time and money*. #### Packages written by others As mentioned before, npm has thousands of modules available for your use. These modules include functionality such as coloring text in your terminal, taking command line input, getting Chuck Norris jokes, and even full-blown web frameworks! This makes it so you don't have to reinvent the wheel with each new project. We'll take a look at some of the more important modules over the coming weeks. ## Installation If you installed Node, chances are you already have npm installed! Test this by running the following command in the terminal: :::info lecture VĂ©rifions que `npm` est bien installĂ© : ::: ``` $ npm --version ``` If you receive a version number, you're good to go! ## Installing Packages To install packages for use in our program, first, we must define our **manifest file**. A _manifest file_ is a file that lists out all the packages our program depends on to function. With npm, this file is going to be called `package.json`. This file will define all of our projects packages and dependencies. Run the following commands in your terminal: :::info lecture CrĂ©ons un projet `npm-getting-started` : ::: ```shell $ mkdir npm-getting-started $ cd npm-getting-started $ npm init ``` This will prompt you with a bunch of different questions. Feel free to hit return until the prompt says: `Is this ok? (yes) yes`, then type "yes". :::info lecture Remarquons la prĂ©sence de `package.json` une fois `npm init` exĂ©cutĂ©e. ::: If you notice, this created a file called `package.json`. This is a JSON formatted file that specifies all of the modules your project will use and other information about your project. :::info :memo: If you're not familiar with **JSON**, don't worry! You will be during this module. ::: Let's install our first module! :::info lecture Installons notre premier module `chalk` : ::: ``` $ npm install chalk ``` `npm install` goes to the npm servers and grabs a package called "chalk". Since Node version 5, the package gets automatically added as a dependency to our package.json. :::info lecture Parlons du dossier `node_modules/` ::: Also, we've created a `node_modules` folder. This is where the actual code for the `chalk` module is stored. :::info :eyes: In older versions of Node, you have to use the `--save` option to save the package's name in your `package.json` (as in `npm install --save chalk`). If you see that in your searches, feel free to omit it. ::: Let's use it! :::info lecture Ecrivons notre programme et utilisons `chalk` : ::: ```shell $ touch index.js $ code index.js ``` And then inside of `index.js`: ```javascript= var chalk = require('chalk'); console.log(chalk.blue('Hello, npm!')); ``` - L1: Firstly, we `require` the module and assign it to a variable. - L3: Then, we can call upon this variable and its attached `blue` method. How do you know which methods are available to you? Well, the documentation has all the answers. :wink: :::info lecture ExĂ©cutons notre programme avec Node : ::: ``` $ node index.js Hello npm ``` You can see all the functionality Chalk makes available by visiting [its documentation page](https://www.npmjs.com/package/chalk). A quality package has proper documentation for people to learn how to use it. Chalk is super cool, but it's just one of many `npm` packages. If you commit only `package.json`, any user will be able to recreate your `node_modules` by simply running `npm install`. :::danger :bomb: <b>**Never commit `node_modules` to git**</b>. It will make your repository a lot larger. Your `node_modules` may also not work on another computer. Everyone has to install npm packages for themselves with `npm install`. ::: :::info There's a shorthand for `npm install`—you can type just **`npm i`**. :star2: ::: ## Exercise Install a package from [this list of npm packages](https://github.com/sindresorhus/awesome-nodejs#weird), specifically the "weird" section. Use the installed package in your `index.js`. See its documentation to learn what it can do and how to use it. ## Summary In this lesson we learned a bit about Node.js, it's history, and how to install it on our computer. Also, we learned a bit about what a *runtime* is. You don't need to know the history of Node to get started, but it is essential to understand the relationship of Node and JavaScript to avoid looking silly in interviews in the future. :exclamation: **It's important to remember that Node is not a framework or a language**. In the next lesson, we will learn a bit about how to install external packages for Node. ## Extra Resources - [Node.js - the official docs](https://nodejs.org/en/docs/) - [Getting the best out of NPM](https://jsblog.insiderattack.net/getting-the-best-out-of-npm-b73d4a8fbf29#.hehmw1xun) - More advanced NPM concepts