<style>
.reveal {
font-size: 28px;
}
</style>
### Introduction to Node.js, npm, and Server-Side JavaScript

---
## Overview
**Session Goals:**
- Understand what Node.js is and why it's useful for server-side development.
- Learn about npm (Node Package Manager) and its role in managing project dependencies.
- Get a glimpse into writing server-side JavaScript with Node.js.
---
## What is Node.js?
> Node.js is an open-source, cross-platform JavaScript runtime environment and library for running web applications outside the client's browser.
---
**Definition and Brief History:**
- Node.js is an open-source, cross-platform JavaScript runtime environment.
- It allows developers to run JavaScript on the server-side, extending JavaScript's reach beyond the browser.
- Created by Ryan Dahl in 2009, Node.js was built on the V8 JavaScript engine developed by Google.
---
**Key Features:**
- **Asynchronous and Event-Driven**: Node.js uses a non-blocking I/O model, making it lightweight and efficient for data-intensive real-time applications.
- **Single Programming Language**: Write both client-side and server-side code in JavaScript, leading to more uniform and streamlined development.
- **Rich Ecosystem**: With npm, Node.js has one of the largest ecosystems of open-source libraries in the world.
---
**Why Node.js for Server-Side Development?**
- It's fast and scalable, thanks to its non-blocking architecture.
- JavaScript ubiquity makes it an accessible choice for many developers.
---
Node.js has not just been a technology but a catalyst in the evolution of web development, leading us into an era of full-stack JavaScript. This means we don't have to learn separate languages for server and client side - we can do everything in JavaScript!
---
## Node.js Architecture
Understanding the architecture of Node.js is key to appreciating its efficiency and performance in server-side applications.
---
**Event-driven, Non-blocking I/O Model:**
- Node.js operates on an event-driven, non-blocking I/O model.
- This means Node.js servers do not wait for an API to return data. Instead, they move to the next API after calling it and a notification mechanism of Node.js Event Loop helps the server to get a response from the previous API call.
- Ideal for handling numerous simultaneous connections with minimal overhead.
---
**V8 JavaScript Engine:**
- Node.js uses the V8 JavaScript engine developed by Google for Chrome.
- V8 compiles JavaScript directly to native machine code, providing high performance and speed.
- Continuous improvements in the V8 engine enhance Node.js performance over time.
---
## Node.js Script
Now that we have Node.js installed, let's write our first server-side JavaScript code. It's just like writing JavaScript for the browser, but now we're doing it for the server.
---
**Writing a Simple "Hello, World!" Script:**
1. **Create a New File**: Open your favorite text editor (like VSCode), and create a new file named `hello.js`.
2. **Write Your JavaScript Code**:
- Type in the following code: `console.log('Hello, World!');`
- This line of code is JavaScript, and it will print "Hello, World!" in the terminal.
3. **Save Your File**: Make sure to save it in a place you can easily find.
---
**Running the Script with Node.js:**
1. **Open Your Terminal**: This is where you'll run your Node.js script.
2. **Navigate to Your File**: Use the `cd` command to navigate to the folder where you saved `hello.js`.
3. **Run Your Script**:
- Type `node hello.js` and press enter.
- You should see `Hello, World!` printed in the terminal.
---
**What's Happening Here?**
- Unlike JavaScript in a browser that can manipulate web pages, here our script is interacting with the terminal.
- Node.js is running your JavaScript file and executing the commands inside it.
---
## Introduction to npm (Node Package Manager)
npm is like a superstore for JavaScript packages. Just as you include CSS frameworks or JavaScript libraries in your web projects, npm lets you easily add and manage code packages in your Node.js applications.
---
**What is npm?**
- npm stands for Node Package Manager.
- It's the world's largest software registry, containing over a million packages of reusable code.
- npm is both an online platform where you can find packages and a command-line tool you install with Node.js.
---
**Core Functionalities:**
1. **Installing Packages**: You can add new packages to your project with a simple command, like `npm install express`.
2. **Managing Dependencies**: npm also tracks the packages your project needs in a file called `package.json`, ensuring everyone working on the project has the same tools.
---
**Why is npm Important?**
- It saves time. Instead of writing code from scratch, you can use packages created by other developers.
- It ensures consistency. `package.json` keeps track of package versions, so your project works smoothly for everyone.
---
npm comes with Node.js. In the next slides, we'll see npm in action and understand how it's an indispensable tool for modern web development.
---
## Creating a Node.js Project
Now, let's start our journey into building a Node.js project. It's like setting up your workspace before you begin creating a website.
---
**Initializing a New Project with `npm init`:**
1. **Create a New Directory**: Make a new folder on your computer where you want your project to live.
2. **Open Your Terminal**: Navigate to your new folder using the `cd` command.
3. **Run `npm init`**:
- Type `npm init` in your terminal and press enter.
- You'll be asked a series of questions (like project name, version, etc.). You can press enter to accept the default for now.
- This process creates a `package.json` file in your project directory.
---
**Understanding `package.json`:**
- Think of `package.json` as the blueprint or recipe for your project.
- It lists the details about your project and the packages (dependencies) it needs to run.
- Whenever you add a new package with npm, it gets listed in this file.
---
**Why is `package.json` Important?**
- It keeps track of your project settings and dependencies.
- When sharing your project, others can use `package.json` to install all the necessary packages in one go.
---
## Adding Dependencies with npm
Adding dependencies with npm is like picking tools and materials for your web project. Let's see how you can easily add external packages to your Node.js project.
---
**How to Install Packages:**
1. **Find a Package**: You can search for packages on the [npm website](https://www.npmjs.com/), which is like a catalog of tools.
2. **Install a Package**:
- In your terminal, navigate to your project directory.
- To install a package, type `npm install <package_name>`. For example, `npm install express`.
- npm will download the package and add it to your `node_modules` folder.
---
**Understanding Local vs Global Installation:**
- **Local Installation** (default): Installs the package in your project directory. It's accessible only within this project.
- **Global Installation**: Installs the package system-wide. Useful for tools you want to use across multiple projects.
---
**`node_modules` and Version Control:**
- The `node_modules` directory is where npm stores the installed packages.
- It's common practice to exclude this folder from version control (like Git) using a `.gitignore` file. Why? Because your `package.json` file already keeps track of what packages your project needs. Anyone who gets your project can install these packages using `npm install`.
---
With npm, managing and sharing your project dependencies becomes a breeze. It ensures everyone working on the project has the same set of tools, making collaboration smooth and efficient.
---
## Building a Simple Web Server
Let's put what we've learned into practice by creating a basic web server with Node.js. This is like setting up a small shop where your web pages can be visited.
---
## Building a Simple Web Server with Express.js
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node.js based web applications.
---
**Basic Setup with Express.js:**
1. **Install Express**: First, make sure you have Express installed in your project. Run `npm install express`.
2. **Write the Server Code**:
- Import Express: `const express = require('express');`
- Initialize your Express app: `const app = express();`
- Define a route: `app.get('/', (req, res) => res.send('Hello, World!'));`
- Listen on a port: `app.listen(3000, () => console.log('Server running on http://localhost:3000'));`
---
**Example Code:**
```javascript
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
```
---
**Running the Server and Testing It in a Browser:**
- In your terminal, run `node server.js`.
- Open a web browser and go to `http://localhost:3000/`.
- You should see "Hello, World!" displayed.
We've just built and run your first web server using Node.js. This is a basic example, but it's the foundation for more complex server functionalities you'll learn in the future.
---
**What's Happening Here?**
- The server is listening on port 3000. When you visit `localhost:3000`, it responds with the text you programmed.
- This is how back-end development works: servers wait for requests and send back responses based on the request received.
---
## Understanding `package.json`
The `package.json` file in a Node.js project is like the identity card of your project. It holds crucial information about your project and how it should run.
---
**What is `package.json`?**
- It's a JSON file that exists at the root of every Node.js project.
- It includes metadata about the project, like the project name, version, and author.
---
**Key Components of `package.json`:**
1. **Dependencies**: These are the packages your project needs to run in production. For example, if your project is a web app, you might need `express`.
2. **devDependencies**: These are the packages required for development and testing, but not for running the app. For example, testing frameworks like `jest` or build tools like `webpack`.
3. **Scripts**: Handy shortcuts you can define to run various tasks. For example, `start` to run your app or `test` to run your tests.
4. **Metadata**: Information about the project, like the `name`, `version`, `description`, and `author`.
---
**Example of a `package.json` file:**
```json
{
"name": "my-awesome-app",
"version": "1.0.0",
"description": "A great Node.js app",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Your Name",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"jest": "^26.6.3"
}
}
```
---
## Conclusion and Resources
**Key Takeaways:**
- **Node.js** is a powerful JavaScript runtime that lets you run JavaScript on the server-side.
- **npm** helps manage packages and dependencies in your Node.js projects.
- We've seen how to set up a Node.js environment, write a simple script, and manage packages with npm.
- Remember, the journey into Node.js is about building on these foundations and exploring more as you go.
---
**Additional Resources:**
- [Node.js Official Documentation](https://nodejs.org/en/docs/) - Great for in-depth learning.
- [Code with Mosh intro to Node.js](https://www.youtube.com/watch?v=TlB_eWDSMt4&ab_channel=ProgrammingwithMosh) - Great introduction to Node
---