DEV Community

Node.js for Server-Side Development

Introduction

Node.js is a powerful, event-driven, non-blocking I/O JavaScript runtime built on Chrome's V8 JavaScript engine. Designed to build scalable network applications, Node.js enables developers to use JavaScript to write server-side code, creating a unified development experience across the entire application stack. This guide provides an in-depth look at Node.js, its core features, and practical examples to illustrate its capabilities in server-side development.

Core Features of Node.js

  1. Asynchronous and Event-Driven: Node.js is designed to handle asynchronous I/O operations, making it ideal for developing scalable and high-performance applications. This means that operations such as reading from the file system or making network requests do not block the execution of other code.

  2. Single-Threaded Event Loop: While Node.js operates on a single thread, it uses an event loop to manage multiple connections simultaneously, making it highly efficient in handling concurrent operations.

  3. Non-Blocking I/O: The non-blocking I/O model allows Node.js to handle multiple operations without waiting for any single operation to complete, enhancing performance and scalability.

  4. NPM (Node Package Manager): NPM is the largest ecosystem of open-source libraries in the world, providing a vast repository of modules and packages that can be easily integrated into Node.js applications.

  5. Cross-Platform: Node.js is cross-platform, meaning it can run on Windows, macOS, and Linux, making it versatile for different development environments.

Setting Up Node.js

To get started with Node.js, you need to install it on your machine. You can download the installer from the official Node.js website.
Once installed, you can verify the installation by opening your terminal or command prompt and typing:

node -v


Enter fullscreen mode Exit fullscreen mode

This command will display the installed Node.js version.

Building a Simple HTTP Server

One of the fundamental tasks in server-side development is creating an HTTP server. Here's how you can create a simple HTTP server using Node.js:

// Import the http module
const http = require('http');

// Define the hostname and port
const hostname = '127.0.0.1';
const port = 3000;

// Create the server
const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!\n');
});

// Start the server
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});


Enter fullscreen mode Exit fullscreen mode

In this example, we import the http module, define the server's hostname and port, create a server instance, and specify the response to be sent to the client. Finally, we start the server and listen on the specified port.

Handling Routes

To handle different routes and HTTP methods, we can use the httpmodule or leverage a framework like Express.js for more advanced routing capabilities. Here's an example using the http module:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  if (req.url === '/' && req.method === 'GET') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Welcome to the Homepage!\n');
  } else if (req.url === '/about' && req.method === 'GET') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('About Us page\n');
  } else {
    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Page Not Found\n');
  }
});

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

Enter fullscreen mode Exit fullscreen mode

In this example, we handle two routes: the homepage (/) and the about page (/about). For any other route, we return a 404 error.

Using Express.js for Enhanced Development

While the http module provides basic server functionality, Express.js is a minimal and flexible Node.js web application framework that offers robust features for web and mobile applications. It simplifies route handling, middleware integration, and more.

Installing Express.js

To install Express.js, use NPM:

npm install express

Enter fullscreen mode Exit fullscreen mode

Creating an Express.js Server

Here's how you can create a simple server using Express.js:

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Welcome to the Homepage!');
});

app.get('/about', (req, res) => {
  res.send('About Us page');
});

app.use((req, res) => {
  res.status(404).send('Page Not Found');
});

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

Enter fullscreen mode Exit fullscreen mode

In this example, we use Express.js to create a server with two routes and a middleware to handle 404 errors.

Interacting with a Database

Node.js can interact with various databases, including SQL and NoSQL databases. MongoDB, a NoSQL database, is commonly used with Node.js due to its JSON-like documents.

Connecting to MongoDB

First, install the MongoDB client library:

npm install mongodb

Enter fullscreen mode Exit fullscreen mode

Then, you can connect to MongoDB and perform operations:

const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';

(async function() {
  const client = new MongoClient(url, { useUnifiedTopology: true });
  try {
    await client.connect();
    console.log('Connected to database');
    const db = client.db(dbName);

    // Insert a document
    const result = await db.collection('mycollection').insertOne({ name: 'John', age: 30 });
    console.log('Document inserted:', result.insertedId);

    // Find documents
    const docs = await db.collection('mycollection').find({}).toArray();
    console.log('Documents found:', docs);
  } catch (err) {
    console.error(err);
  } finally {
    await client.close();
  }
})();

Enter fullscreen mode Exit fullscreen mode

In this example, we connect to a MongoDB database, insert a document, and retrieve documents from a collection.

Conclusion

Node.js is a versatile and powerful runtime for server-side development, enabling developers to build scalable and efficient applications. With its asynchronous, event-driven architecture and extensive ecosystem, Node.js provides the tools necessary for modern web development. By leveraging frameworks like Express.js and integrating with databases like MongoDB, developers can create robust and high-performance server-side applications.

Top comments (0)