JavaScript on the Server (Node.js Intro)

Introduction to Node.js

JavaScript has traditionally been used in the browser for front-end development, but with the introduction of Node.js, JavaScript has made its way to the back-end. Node.js allows developers to write server-side applications using JavaScript. It’s fast, scalable, and uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

In this module, we’ll dive into the basics of Node.js, explore its core concepts, and set up a simple Node.js server.


Table of Contents

  1. What is Node.js?
  2. Features of Node.js
  3. Installing Node.js
  4. Writing Your First Node.js Application
  5. Understanding the Event Loop
  6. Modules in Node.js
  7. Setting Up a Simple HTTP Server
  8. Conclusion

1. What is Node.js?

Node.js is a JavaScript runtime environment built on Chrome’s V8 JavaScript engine. It was created to build scalable network applications. With Node.js, you can use JavaScript to handle HTTP requests, interact with databases, and serve data to clients, just like other back-end programming languages such as Python, Ruby, or PHP.

Node.js allows you to run JavaScript code outside the browser on the server. It’s particularly known for its non-blocking, event-driven architecture that makes it ideal for I/O-heavy applications like real-time chat apps, online gaming servers, and APIs.


2. Features of Node.js

Node.js is designed for building fast and scalable applications. Here are some key features:

  • Event-driven, Non-blocking I/O: This allows Node.js to handle multiple operations concurrently, making it ideal for real-time applications like chat apps or live notifications.
  • Single-threaded: Node.js operates on a single thread, which is great for scaling. It uses asynchronous calls to handle multiple requests without needing extra threads.
  • Fast Execution: Built on Chrome’s V8 engine, Node.js executes JavaScript code at lightning speed.
  • NPM (Node Package Manager): Node.js comes with a package manager called npm, which allows you to easily install and manage libraries and dependencies for your project.
  • Cross-platform: Node.js is cross-platform, meaning it can run on any operating system, such as Linux, macOS, or Windows.

3. Installing Node.js

To start using Node.js, you need to install it on your computer. Here’s how to get started:

  1. Go to the Node.js download page.
  2. Download the LTS (Long Term Support) version for stability.
  3. Follow the installation instructions for your operating system.
  4. Once installed, open your terminal (or command prompt on Windows) and check if the installation was successful by running: bashCopyEditnode -v npm -v

This will display the installed versions of Node.js and npm.


4. Writing Your First Node.js Application

Once Node.js is installed, you can write your first Node.js application. Let’s start by creating a simple “Hello World” server:

Steps to Create Your First Node.js App:

  1. Create a new directory for your project: mkdir my-node-app cd my-node-app
  2. Create a new file called app.js: bashCopyEdittouch app.js
  3. Open app.js in your text editor and add the following code to create a basic HTTP server: const http = require('http'); // Import the HTTP module const server = http.createServer((req, res) => { // Create an HTTP server res.statusCode = 200; // Set HTTP status code res.setHeader('Content-Type', 'text/plain'); // Set response header res.end('Hello, Node.js!\n'); // Send response }); const port = 3000; // Specify the port number server.listen(port, () => { // Start the server and listen on port 3000 console.log(`Server running at http://localhost:${port}/`); });
  4. In the terminal, run the Node.js server: node app.js
  5. Open your browser and go to http://localhost:3000. You should see the text Hello, Node.js!.

This simple example demonstrates how to use Node.js to create an HTTP server that listens for incoming requests and sends a response.


5. Understanding the Event Loop

Node.js is based on an event-driven architecture. This means it handles asynchronous operations (such as reading files or handling HTTP requests) without blocking the execution of other code.

  • The Event Loop is a mechanism that continually checks for events or messages in the system and processes them in a non-blocking way.
  • When Node.js executes asynchronous code (e.g., file reads, network requests), it doesn’t wait for the result but continues executing other code, ensuring that the system remains responsive.

For instance, Node.js can handle thousands of concurrent requests without being blocked by I/O operations.


6. Modules in Node.js

Node.js comes with a set of built-in modules that you can use to perform various tasks. These modules encapsulate functionality and make it easier to work with different aspects of the application.

Some Common Modules:

  • HTTP: To create web servers and handle HTTP requests.
  • FS (File System): For reading from and writing to the file system.
  • Path: To work with and manipulate file and directory paths.
  • OS: Provides operating system-related utility methods (e.g., to get system information).
  • Events: Used to handle and emit events.

You can also install third-party modules using npm. For example, to work with databases like MongoDB, you can install the MongoDB driver using npm.

Example of Using the fs Module:

const fs = require('fs');

// Writing to a file
fs.writeFile('example.txt', 'Hello, Node.js File System!', (err) => {
if (err) throw err;
console.log('File has been saved!');
});

7. Setting Up a Simple HTTP Server

In this section, we’ll dive deeper into building a more interactive HTTP server with Node.js.

Let’s enhance the previous HTTP server by making it dynamic. Instead of responding with the same text for all requests, we will check the URL and respond accordingly.

const http = require('http');

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');

if (req.url === '/') {
res.end('Welcome to the Home Page!');
} else if (req.url === '/about') {
res.end('Welcome to the About Page!');
} else {
res.statusCode = 404;
res.end('Page not found!');
}
});

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

Now, when you visit http://localhost:3000/, you’ll get a welcome message, and if you go to http://localhost:3000/about, you’ll see the about page message. If you navigate to any other URL, it’ll return a 404 error.


8. Conclusion

Node.js brings JavaScript to the server side, allowing developers to write full-stack applications using the same language throughout. In this module, you learned about:

  • What Node.js is and its core features.
  • How to install Node.js and set up a basic development environment.
  • Writing your first Node.js HTTP server.
  • Understanding how asynchronous, non-blocking I/O works in Node.js with the event loop.
  • Exploring Node.js modules like http, fs, and path.

With this foundation, you’re ready to explore more advanced Node.js concepts and start building server-side applications!