Title: Setting Up the Node.js Environment
Objective: By the end of this chapter, students will be able to set up a Node.js development environment, understand version management, and create a basic Node.js project following best practices.
A. Installing Node.js and npm
Goal: Install Node.js and npm (Node Package Manager) on the local machine to start working with Node.js applications.
Steps:
-
Download Node.js:
- Visit the official Node.js website.
- Choose the LTS (Long-Term Support) version for stability, especially for production environments.
- Download and run the installer for your operating system (Windows, macOS, or Linux).
-
Installation Process:
- Follow the installation prompts.
- Ensure that the installer adds Node.js and npm to your system PATH.
-
Verify Installation:
- Open a terminal or command prompt.
- Check the installed versions by running:
node -v npm -v - This should output the installed versions of Node.js and npm.
Example:
$ node -v
v18.14.0
$ npm -v
9.4.2
B. Using nvm for Node.js Version Management
Goal: Install and use nvm (Node Version Manager) to manage multiple versions of Node.js.
Steps:
-
Install nvm:
- For macOS and Linux:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash - For Windows, use nvm-windows as the official nvm is not available for Windows.
- For macOS and Linux:
-
Verify nvm Installation:
- Restart your terminal and run:
nvm -v
- Restart your terminal and run:
-
Install and Switch Node.js Versions:
- List available Node.js versions:
nvm list-remote - Install a specific version:
nvm install 16.13.0 - Switch to a different version:
nvm use 16.13.0 - Set a default Node.js version:
nvm alias default 16.13.0
- List available Node.js versions:
Example:
$ nvm install 18.14.0
$ nvm use 18.14.0
Best Practices:
- Use LTS versions for production environments.
- Keep the development environment consistent by using
nvmacross team members.
C. Understanding the Node.js REPL
Goal: Explore the Read-Eval-Print Loop (REPL) for experimenting with Node.js code in an interactive shell.
Steps:
-
Start REPL:
- In the terminal, type
nodeand press Enter. - You should see a
>prompt, indicating the REPL is active.
- In the terminal, type
-
Basic Operations in REPL:
- Mathematical Operations:
> 5 + 10 15 - Variable Declarations:
> let x = 20; > x * 2 40 - Functions:
> function greet(name) { return `Hello, ${name}!`; } > greet('World') 'Hello, World!'
- Mathematical Operations:
-
Exit REPL:
- To exit, type
.exitor pressCtrl + Ctwice.
- To exit, type
Best Practices:
- Use REPL for quick testing and debugging of small pieces of code.
- Use the
.savecommand to save the session to a file if needed.
D. Setting Up a Basic Node.js Project
Goal: Create a new Node.js project and set up a basic project structure.
Steps:
-
Create a Project Directory:
mkdir my-node-project cd my-node-project -
Initialize the Project:
- Run the following command to create a
package.jsonfile:npm init -y - This file contains metadata about the project and lists dependencies.
- Run the following command to create a
-
Create a Basic Project Structure:
- Inside the project directory, create the following folders and files:
my-node-project/ ├── src/ │ └── index.js ├── test/ ├── node_modules/ ├── package.json └── .gitignore
- Inside the project directory, create the following folders and files:
-
Add Basic Code:
- In
src/index.js, add a simple "Hello World" code:console.log("Hello, Node.js!");
- In
-
Run the Project:
- In the terminal, execute:
node src/index.js
- In the terminal, execute:
Example Output:
Hello, Node.js!
Best Practices:
- Use meaningful directory and file names.
- Keep your project structure modular and organized.
E. Introduction to package.json
Goal: Understand the purpose and structure of the package.json file in a Node.js project.
Key Fields:
-
name: The name of your project.
"name": "my-node-project", -
version: The current version of your project.
"version": "1.0.0", -
description: A short description of your project.
"description": "A basic Node.js project setup example", -
main: The entry point of your project.
"main": "src/index.js", -
scripts: Define scripts that can be run using npm.
"scripts": { "start": "node src/index.js", "test": "echo \"Error: no test specified\" && exit 1" }, -
dependencies: List of dependencies required for the project.
"dependencies": { "express": "^4.17.1" } -
devDependencies: List of development dependencies.
"devDependencies": { "nodemon": "^2.0.7" } -
license: The license under which the project is distributed.
"license": "MIT",
Best Practices:
- Keep your
package.jsonclean and well-documented. - Use semantic versioning (
major.minor.patch) for versioning your project.
F. Configuring Environment Variables
Goal: Set up environment variables to manage sensitive information and configure your Node.js application for different environments.
Steps:
-
Create an
.envFile:- In the project root, create an
.envfile:PORT=3000 DATABASE_URL=mongodb://localhost:27017/mydb
- In the project root, create an
-
Install
dotenvPackage:npm install dotenv -
Load Environment Variables in Your Project:
-
In your
src/index.jsfile, add the following code:require("dotenv").config(); const port = process.env.PORT || 3000; console.log(`Server running on port ${port}`);
-
-
Access Environment Variables:
- Use
process.env.VARIABLE_NAMEto access environment variables in your code.
- Use
-
Ignore
.envFile:- Add
.envto your.gitignorefile to prevent it from being committed to version control:node_modules/ .env
- Add
Best Practices:
- Keep sensitive information such as API keys, database credentials, and secret tokens in environment variables.
- Use different
.envfiles for different environments (e.g.,.env.development,.env.production).
Summary
In this chapter, you've learned how to set up the Node.js environment, manage Node.js versions with nvm, and create a basic Node.js project. You've also gained an understanding of the Node.js REPL, the structure and importance of the package.json file, and how to configure environment variables effectively. These foundational skills are essential for developing robust and maintainable Node.js applications.
Next Chapter: Working with Node.js Modules and NPM