Server-Side JavaScript with Node.js

Server-Side JavaScript with Node.js

ยท

2 min read

This guide provides examples of server-side JavaScript using Node.js. It covers the basics of setting up a server, designing a RESTful API, interacting with a database, and understanding server architecture.

Table of Contents

Setting Up a Basic Node.js Server

To set up a basic Node.js server, you need to have Node.js installed on your system. Once installed, you can create a simple server as follows:

const http = require('http');

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

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

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

Creating a Simple RESTful API

Using the Express framework makes it easier to design RESTful APIs. First, install Express via npm:

npm install express

Then, you can set up a basic API as follows:

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

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.get('/api/users', (req, res) => {
  res.json([{ name: 'John Doe' }, { name: 'Jane Doe' }]);
});

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

Database Interactions

For simplicity, let's use a pseudo database interaction:

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

let users = [{ name: 'John Doe' }, { name: 'Jane Doe' }];

app.get('/api/users', (req, res) => {
  res.json(users);
});

app.post('/api/users', (req, res) => {
  // Add a new user (simplified)
  users.push({ name: 'New User' });
  res.status(201).send('User added');
});

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

Understanding Server Architecture

In server-side JavaScript, especially with Node.js, understanding server architecture is crucial. Node.js allows for event-driven, non-blocking I/O models, making it efficient for real-time applications on distributed systems. When designing your server architecture, consider aspects like scalability, maintainability, and security.

Remember, this is a simplified guide aimed at demonstrating the basics of server-side JavaScript with Node.js. For a real-world application, you would need to delve deeper into each of these topics.

ย