Node.js Get Started

Subject: Node.js

Node.js enables you to build fast, scalable network applications using JavaScript outside the browser. In this chapter, you will learn how to set up a Node.js development environment and run your first real-world applications.

1. Installing Node.js and npm

To get started with Node.js development, first install Node.js and npm (Node Package Manager).

Step 1: Download and Install

  • Go to: https://nodejs.org
  • Download and install the LTS (Long-Term Support) version for your operating system.

Step 2: Verify Installation Open your terminal or command prompt and run the following commands:

Example Output:

This confirms that both Node.js and npm are installed correctly.


2. Create Your First Node.js File

Let’s write a basic Node.js program.

File: app.js

Run the Program:

Output:

Explanation: This code prints a message to the terminal using console.log(), confirming Node.js is set up and working correctly.


3. Creating a Simple Web Server

Node.js includes a built-in http module for building web servers.

File: server.js

Run the Server:

Output in Terminal:

Output in Browser:

Explanation:

  • http.createServer() creates the HTTP server.
  • res.writeHead() sets response headers.
  • res.end() sends the response.
  • .listen(3000) starts the server on port 3000.

4. Using Node.js REPL

Node.js provides a REPL (Read-Eval-Print Loop) to test JavaScript code interactively.

Start REPL:

Then type commands directly:

Explanation: REPL lets you test small code snippets quickly, without creating files.


5. Node.js File Extensions

  • Default Node.js files use .js extension.
  • Files using ES Modules can use .mjs.
  • Most Node.js projects use .js.

6. Recommended Directory Structure

Organizing your project this way makes it more readable and scalable.


Key Takeaways

  • Node.js runs JavaScript on the server.
  • Use node <filename> to execute files.
  • Create web servers using the built-in http module.
  • Use REPL for interactive code testing.
  • Maintain organized directory structures for real-world apps.
Next : Node Intro