> ## Documentation Index
> Fetch the complete documentation index at: https://docs.loremstock.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Setting Up the Node.js Development Environment

> Learn to install Node.js, understand npm, initialize a project, and configure package.json for backend development with Express.

Node.js is the foundation of every topic in this course. Before writing any API code, students need to understand what Node.js is, how it runs, and how to organize a project. This page explains the runtime, the package system, and the essential tools to build backend applications.

## What Is Node.js?

**Node.js** is a JavaScript runtime environment built on Chrome's **V8 engine**. It allows JavaScript code to run on a server (outside the browser). Before Node.js, JavaScript could only run in browsers.

### Key characteristics

| Feature              | Explanation                                                                                        |
| -------------------- | -------------------------------------------------------------------------------------------------- |
| **Event-driven**     | Node.js uses events to trigger callbacks instead of waiting for operations to finish               |
| **Non-blocking I/O** | While waiting for a file read or database query, Node continues processing other requests          |
| **Single-threaded**  | One thread handles all requests using the event loop (no multi-threading needed for most web apps) |
| **V8 engine**        | The same JavaScript engine that powers Google Chrome, offering fast execution                      |

<Note>
  Non-blocking I/O is what makes Node.js excellent for APIs and web servers. It handles many concurrent requests efficiently without spawning extra threads.
</Note>

## The Event Loop (Simplified)

The event loop is Node.js's mechanism for handling asynchronous operations:

1. **Call Stack** — executes synchronous code line by line
2. **Node APIs** — handles async operations (fs, http, timers)
3. **Callback Queue** — queues completed async callbacks
4. **Event Loop** — moves callbacks from the queue to the call stack when it is empty

```javascript theme={null}
console.log('1 - synchronous');

setTimeout(() => {
  console.log('3 - async callback');
}, 0);

console.log('2 - synchronous');

// Output:
// 1 - synchronous
// 2 - synchronous
// 3 - async callback
```

<Note>
  Even with a 0ms timeout, the callback runs last because it goes through the event loop. This is fundamental to understanding asynchronous Node.js behavior.
</Note>

## npm: Node Package Manager

npm is the default package manager for Node.js. It lets you install, manage, and share reusable code packages from the npm registry.

### Essential npm commands

```bash theme={null}
# Initialize a new project (creates package.json)
npm init -y

# Install a production dependency
npm install express

# Install a dev-only dependency
npm install --save-dev nodemon

# Install a specific version
npm install express@4.18.2

# Uninstall a package
npm uninstall express

# Install all dependencies from package.json
npm install

# List installed packages
npm list

# Check for outdated packages
npm outdated
```

## Understanding package.json

`package.json` is the project manifest. Every Node.js project has one.

```json theme={null}
{
  "name": "my-api",
  "version": "1.0.0",
  "description": "A sample REST API",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "jest"
  },
  "dependencies": {
    "express": "^4.18.2",
    "mongoose": "^7.6.0"
  },
  "devDependencies": {
    "nodemon": "^3.0.0",
    "jest": "^29.0.0"
  }
}
```

| Field             | Purpose                                           |
| ----------------- | ------------------------------------------------- |
| `name`            | Package name (lowercase, no spaces)               |
| `version`         | Current version using semver (MAJOR.MINOR.PATCH)  |
| `main`            | Entry point file                                  |
| `scripts`         | Custom commands you can run with `npm run <name>` |
| `dependencies`    | Packages needed in production                     |
| `devDependencies` | Packages needed only during development           |

## nodemon for Development

`nodemon` watches your files and restarts the server automatically when code changes. Essential for development.

```bash theme={null}
npm install --save-dev nodemon
```

```json theme={null}
{
  "scripts": {
    "dev": "nodemon index.js"
  }
}
```

```bash theme={null}
npm run dev
# Server restarts on every file save
```

## require() vs import/export

Node.js supports two module systems. You must know both.

<CodeGroup>
  ```javascript CommonJS (ES5) theme={null}
  // Import
  const express = require('express');
  const { helper } = require('./utils');

  // Export
  module.exports = { myFunction };
  module.exports = myFunction;
  ```

  ```javascript ES Modules (ES6) theme={null}
  // Import
  import express from 'express';
  import { helper } from './utils.js';

  // Export
  export { myFunction };
  export default myFunction;
  ```
</CodeGroup>

To use ES Modules, add to `package.json`:

```json theme={null}
{
  "type": "module"
}
```

<Warning>
  You cannot mix `require()` and `import` in the same file. Choose one module system per project.
</Warning>

## Your First HTTP Server (Built-in http module)

Before using Express, understand how Node's built-in `http` module works. This is what Express wraps.

```javascript theme={null}
// server.js
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ message: 'Hello from Node.js!' }));
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});
```

Run it:

```bash theme={null}
node server.js
```

## Your First Express Server

Express makes building servers much easier:

```bash theme={null}
npm install express
```

```javascript theme={null}
// index.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json()); // Parse incoming JSON

app.get('/', (req, res) => {
  res.status(200).json({ message: 'Hello World!' });
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
```

```bash theme={null}
node index.js
# Test: curl http://localhost:3000
```

## .gitignore: What to Exclude

Always create a `.gitignore` before your first commit:

```bash theme={null}
# .gitignore
node_modules/
.env
.env.*
*.log
dist/
```

<Warning>
  Never commit `node_modules` (huge and platform-specific) or `.env` (contains secrets). These are the two most critical entries in `.gitignore`.
</Warning>

## Key Terms to Memorize

| Term              | Definition                                                                                      |
| ----------------- | ----------------------------------------------------------------------------------------------- |
| **Runtime**       | The environment that executes code. Node.js is the runtime for server-side JavaScript.          |
| **Event loop**    | The mechanism that enables non-blocking async operations in Node.js.                            |
| **Callback**      | A function passed as an argument to another function, called when an async operation completes. |
| **Package**       | A reusable module of JavaScript code published to the npm registry.                             |
| **Dependency**    | A package your production app needs to run.                                                     |
| **devDependency** | A package needed only during development (testing, linting, hot reload).                        |
| **Semver**        | Semantic versioning: MAJOR.MINOR.PATCH format for package versions.                             |
| **V8**            | Google's JavaScript engine used in Chrome and Node.js.                                          |

## Common Mistakes and Exam Tips

<Accordion title="Forgetting npm install after cloning">
  When you clone a repo, `node_modules` is not included. Always run `npm install` first.
</Accordion>

<Accordion title="Using require and import in the same file">
  This causes a syntax error. CommonJS uses `require/module.exports`. ES Modules uses `import/export`. Pick one per project.
</Accordion>

<Accordion title="Not using nodemon in development">
  Restarting the server manually after every code change is slow. Add nodemon as a dev dependency and use `npm run dev`.
</Accordion>

<Accordion title="Wrong PORT causing EADDRINUSE errors">
  If port 3000 is already in use, change the port or kill the existing process. Use `process.env.PORT || 3000` to read from environment variables.
</Accordion>

<Tip>
  Exam tip: Know the difference between `dependencies` and `devDependencies` in `package.json`. A common question asks which category a package like Jest (testing) or nodemon (dev server) belongs in. Both are `devDependencies`.
</Tip>
