All the Basics of Latest Released Node.js 2024
The new Node.js release has added some fresh, efficient ways to work with servers, making it a great time to start with Node basics. This guide will take you through the fundamental concepts using real code examples, starting with a simple JSON server setup using http. This file, server.js, gives us a taste of how easy it is to build a lightweight, standalone server in Node.js without external frameworks.
Step 1: Setting Up the Node.js Server
File: server.js
// server.js
const http = require('http');
This line imports the built-in http module, which provides functions for setting up an HTTP server. Node.js is modular, so we’re able to pull in only what we need without unnecessary code.
Step 2: Creating the Server and Sending a JSON Response
// Create a server
const server = http.createServer((req, res) => {
// Set the response header to JSON
res.writeHead(200, { 'Content-Type': 'application/json' });
// Send a JSON response
res.end(JSON.stringify({ message: "Hello, this is your JSON message!" }));
});
const server = http.createServer(...): Here, we create a server by passing a function that will handle incoming requests (req) and outgoing responses (res).
Setting the Content-Type Header: We specify that the response content will be JSON using res.writeHead(200, { 'Content-Type': 'application/json' });. The 200 status code means "OK."
Sending the JSON Response: The line res.end(JSON.stringify({ message: "Hello, this is your JSON message!" })); sends a JSON object back to the client. Using JSON.stringify ensures the JavaScript object is converted into JSON format.
Step 3: Defining the Port and Starting the Server
// Define a port
const PORT = 3000;
We set a PORT variable for our server. Ports are like "doors" for our server, allowing us to host different applications on the same machine.
// Start the server
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
The server.listen method binds and listens for incoming connections on the specified port. Once our server starts, it logs a message with the server URL: http://localhost:3000.
Running the Server
To get this server up and running, make sure you have Node.js installed. Then, in your terminal, navigate to the directory where server.js is saved and type:
node server.js
That’s it! You now have a working server responding with JSON
Serving HTML Content by Server
Now, we’ll take the basics of setting up a Node.js server by serving an HTML response. The code here creates a standalone server using Node’s http module to send an HTML page when accessed through a browser or HTTP client.
// server.js
const http = require('http');
This line imports the http module, a built-in Node.js module for creating HTTP servers and handling requests and responses.
Creating the Server to Serve HTML Content
// Create a server
const server = http.createServer((req, res) => {
// Set the response header to HTML
res.writeHead(200, { 'Content-Type': 'text/html' });
// Send an HTML response
res.end(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Node.js Server</title>
</head>
<body>
<h1>Welcome to the Node.js Server</h1>
<p>This is a basic HTML page served from Node.js!</p>
</body>
</html>
`);
});
// Define a port
const PORT = 3000;
// Start the server
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
Here, we define the port on which our server will listen and Finally, server.listen(PORT, () => { ... }) binds our server to the defined port and logs a message in the console once it’s running.
To run the server, use the following command in your terminal:
node server.js
Navigate to http://localhost:3000 in your browser, and you’ll see the HTML page served directly from your Node.js server!
Serving Static HTML Files with Node.js
With this example, we’re creating a Node.js server that can serve a static HTML file, demonstrating how Node.js handles filesystem access to read and serve files directly.
Code File: server.js
// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
// Create a server
const server = http.createServer((req, res) => {
// Set the file path to 'index.html'
const filePath = path.join(__dirname, '3.html');
// Read the HTML file
fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Server Error');
} else {
// Set the response header to HTML
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content);
}
});
});
// Define a port
const PORT = 3000;
// Start the server
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
HTML File: 3.html
<!-- 3.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Node.js HTML Server</title>
</head>
<body>
<h1>Welcome to the Node.js HTML Server</h1>
<p>This is an HTML file served using Node.js!</p>
</body>
</html>
In this example, we’ve created a basic Node.js server that serves an HTML file. The server uses the http, fs, and path modules to read and serve the 3.html file when a request is made.
Serving Images with Node.js
In this example, we will create a Node.js server that serves both a local image file and a remote image from the web, illustrating how to handle different content types in HTTP responses.
// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
// Define the paths
const localImagePath = path.join(__dirname, 'python_gemini_api_01.png');
const remoteImageUrl = 'https://upload.wikimedia.org/wikipedia/commons/c/c4/Unity_2021.svg';
const server = http.createServer((req, res) => {
if (req.url === '/') {
// Serve HTML content with image URLs
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Images served from Node.js</h1>
<h2>Local Image:</h2>
<img src="/python_gemini_api_01.png" alt="Local Image" width="300">
<h2>Remote Image:</h2>
<img src="${remoteImageUrl}" alt="Remote Image" width="300">
</body>
</html>
`);
} else if (req.url === '/python_gemini_api_01.png') {
// Serve the local image directly by checking the filename in the URL
res.writeHead(200, { 'Content-Type': 'image/png' });
fs.createReadStream(localImagePath).pipe(res);
}
});
// Start the server
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
In this implementation of server.js, we are enhancing our Node.js server to serve both local and remote images.
Serving Text File Content with Node.js
In this example, we will build upon our Node.js server to serve the content of a text file, displaying it in a simple HTML format.
// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
// Define the path to the text file
const textFilePath = path.join(__dirname, 'sample.txt');
// Create the server
const server = http.createServer((req, res) => {
// Read the text file
fs.readFile(textFilePath, 'utf8', (err, data) => {
if (err) {
// Handle error if the file cannot be read
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error reading file');
return;
}
// Serve HTML with the text content
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Text File Content</h1>
<pre>${data}</pre>
</body>
</html>
`);
});
});
// Start the server
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
This example illustrates how to serve not just images or HTML but also plain text files using Node.js, highlighting its versatility in handling various file types.
Video Streaming with Node.js
In this example, we will enhance our Node.js server to serve both local and remote video files, allowing users to stream video content directly from their browsers.
// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
// Define paths for local video and remote video URL
const localVideoPath = path.join(__dirname, 'video.mp4');
const remoteVideoUrl = 'https://videos.pexels.com/video-files/3195394/3195394-sd_640_360_25fps.mp4'; // Replace this URL with your own video URL
const server = http.createServer((req, res) => {
if (req.url === '/') {
// Serve HTML with embedded video tags
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Video Streaming in Node.js</h1>
<h2>Local Video:</h2>
<video width="320" height="240" controls>
<source src="/local-video" type="video/mp4">
Your browser does not support the video tag.
</video>
<h2>Remote Video:</h2>
<video width="320" height="240" controls>
<source src="${remoteVideoUrl}" type="video/mp4">
Your browser does not support the video tag.
</video>
</body>
</html>
`);
} else if (req.url === '/local-video') {
// Stream the local video file
fs.stat(localVideoPath, (err, stats) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Local video not found');
return;
}
// Set up video streaming headers
res.writeHead(200, {
'Content-Type': 'video/mp4',
'Content-Length': stats.size
});
// Create a read stream and pipe it to the response
fs.createReadStream(localVideoPath).pipe(res);
});
}
});
// Start the server
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
This implementation of server.js provides a way to stream both local and remote videos through a web interface, showcasing the capabilities of Node.js in handling multimedia content.
By incorporating these features, this example demonstrates how to build a basic media streaming server with Node.js, enabling users to enjoy both local and remote video content seamlessly in their web browsers.
Audio Streaming with Node.js
In this example, we'll build upon our Node.js server to provide audio streaming capabilities, enabling users to listen to both local and remote audio files directly in their web browsers.
// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
// Define paths for the local audio and the remote audio URL
const localAudioPath = path.join(__dirname, 'Bloody_Mary.mp3');
const remoteAudioUrl = 'https://codewithnitiksh.github.io/sample-data/songs/Spektrem_Shine_[NCS_Release].mp3'; // Replace this URL with your desired audio URL
const server = http.createServer((req, res) => {
if (req.url === '/') {
// Serve HTML with embedded audio tags
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Audio Streaming in Node.js</h1>
<h2>Local Audio:</h2>
<audio controls>
<source src="/local-audio" type="audio/mp3">
Your browser does not support the audio tag.
</audio>
<h2>Remote Audio:</h2>
<audio controls>
<source src="${remoteAudioUrl}" type="audio/mp3">
Your browser does not support the audio tag.
</audio>
</body>
</html>
`);
} else if (req.url === '/local-audio') {
// Stream the local audio file
fs.stat(localAudioPath, (err, stats) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Local audio not found');
return;
}
// Set up audio streaming headers
res.writeHead(200, {
'Content-Type': 'audio/mp3',
'Content-Length': stats.size
});
// Create a read stream and pipe it to the response
fs.createReadStream(localAudioPath).pipe(res);
});
}
});
// Start the server
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
This server.js implementation allows users to stream audio files from a Node.js server, featuring both local and remote audio content.
With this setup, you can seamlessly stream both local and remote audio files, providing an engaging listening experience directly through your web browser.
JSON Data Display with Node.js
In this implementation, we'll create a Node.js server that reads data from a JSON file and displays it as an HTML response in the browser. This setup is useful for demonstrating how to serve structured data in a user-friendly format.
Code File: server.js
// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
// Define the path to the JSON data file
const dataFilePath = path.join(__dirname, 'person.json');
const server = http.createServer((req, res) => {
if (req.url === '/') {
// Read the JSON file
fs.readFile(dataFilePath, 'utf8', (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error reading data file');
return;
}
// Parse JSON data for HTML display
const jsonData = JSON.parse(data);
const htmlContent = `
<html>
<body>
<h1>JSON Data</h1>
<ul>
<li><strong>Name:</strong> ${jsonData.name}</li>
<li><strong>Age:</strong> ${jsonData.age}</li>
<li><strong>City:</strong> ${jsonData.city}</li>
<li><strong>Interests:</strong>
<ul>
${jsonData.interests.map(interest => `<li>${interest}</li>`).join('')}
</ul>
</li>
</ul>
</body>
</html>
`;
// Send HTML content as the response
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(htmlContent);
});
} else {
// Handle any other route as 404 Not Found
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
// Start the server
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
JSON File: person.json
{
"name": "John Doe",
"age": 30,
"city": "New York",
"interests": ["coding", "music", "sports"]
}
This server.js implementation serves a simple purpose: it reads a JSON file containing user data and presents it in an HTML format
This simple code serves as a foundational example of how to read JSON data in Node.js and present it in a web-friendly format, making it easier for users to access structured information.
Employee Data from a JSON file
In this implementation, we will create a Node.js server that serves an HTML page displaying employee data from a JSON file. This setup illustrates how to present structured data in a table format using a web interface.
Code File: server.js
// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
// Define the path to the JSON data file
const dataFilePath = path.join(__dirname, 'employees.json');
const server = http.createServer((req, res) => {
if (req.url === '/') {
// Read the JSON file
fs.readFile(dataFilePath, 'utf8', (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error reading data file');
return;
}
// Parse JSON data for HTML display
const employees = JSON.parse(data);
const htmlContent = `
<html>
<head>
<title>Employee Directory</title>
<style>
table { width: 100%; border-collapse: collapse; }
th, td { padding: 8px; border: 1px solid #ddd; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h1>Employee Directory</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Department</th>
<th>Salary</th>
<th>Location</th>
</tr>
${employees.map(employee => `
<tr>
<td>${employee.id}</td>
<td>${employee.name}</td>
<td>${employee.position}</td>
<td>${employee.department}</td>
<td>$${employee.salary.toLocaleString()}</td>
<td>${employee.location}</td>
</tr>
`).join('')}
</table>
</body>
</html>
`;
// Send HTML content as the response
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(htmlContent);
});
} else {
// Handle any other route as 404 Not Found
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
// Start the server
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
JSON File: employees.json
[
{
"id": 1,
"name": "Alice Johnson",
"position": "Software Engineer",
"department": "Engineering",
"salary": 90000,
"location": "New York"
},
{
"id": 2,
"name": "Bob Smith",
"position": "Product Manager",
"department": "Product",
"salary": 105000,
"location": "San Francisco"
},
{
"id": 3,
"name": "Carol Williams",
"position": "UX Designer",
"department": "Design",
"salary": 75000,
"location": "Austin"
},
{
"id": 4,
"name": "David Brown",
"position": "Data Scientist",
"department": "Data",
"salary": 120000,
"location": "Chicago"
},
{
"id": 5,
"name": "Eve Davis",
"position": "Marketing Specialist",
"department": "Marketing",
"salary": 68000,
"location": "Los Angeles"
}
]
This implementation serves as a functional employee directory using Node.js, providing a user-friendly web interface to display employee data stored in a JSON file.
Data from JSON file URL
In this implementation, we create a Node.js server that fetches employee data from an external JSON URL and serves it in an HTML table format. This demonstrates how to integrate external data sources into a Node.js application.
Code File: server.js
// server.js
const http = require('http');
const https = require('https');
// URL of the external JSON data
const jsonDataUrl = 'https://codewithnitiksh.github.io/sample-data/json/employees.json';
const server = http.createServer((req, res) => {
if (req.url === '/') {
// Fetch JSON data from external URL
https.get(jsonDataUrl, (response) => {
let data = '';
// Collect data chunks
response.on('data', (chunk) => {
data += chunk;
});
// When the entire response is received
response.on('end', () => {
// Parse the JSON data
const employees = JSON.parse(data);
// Generate HTML content
const htmlContent = `
<html>
<head>
<title>Employee Directory</title>
<style>
table { width: 100%; border-collapse: collapse; }
th, td { padding: 8px; border: 1px solid #ddd; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h1>Employee Directory</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Department</th>
<th>Salary</th>
<th>Location</th>
</tr>
${employees.map(employee => `
<tr>
<td>${employee.id}</td>
<td>${employee.name}</td>
<td>${employee.position}</td>
<td>${employee.department}</td>
<td>$${employee.salary.toLocaleString()}</td>
<td>${employee.location}</td>
</tr>
`).join('')}
</table>
</body>
</html>
`;
// Send HTML content as the response
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(htmlContent);
});
}).on('error', (err) => {
// Handle request error
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error fetching data');
});
} else {
// Handle any other route as 404 Not Found
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
// Start the server
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
This code demonstrates how Node.js can interact with external APIs or data sources to serve dynamic content, making it a powerful tool for building web applications.
As we conclude this exploration of Node.js through various practical examples, we've seen how this powerful runtime environment can facilitate diverse functionalities, from serving static files to fetching and displaying dynamic content from external APIs. Each code snippet we've discussed serves to illustrate the versatility and simplicity of Node.js for building web applications.
Node.js represents a significant shift in how we think about server-side development. By enabling JavaScript to run on the server, it has opened up new possibilities for developers to create fast, scalable applications. Whether you're building a simple server or a complex web application, Node.js provides the tools and flexibility needed to bring your ideas to life.
Thank you for following along with this blog! We hope it has been informative and inspiring, encouraging you to delve deeper into the world of Node.js and web development. Happy coding!