Hello World: Create a simple Node.js script that outputs "Hello World" to the console. This will help you get started with running Node.js scripts and understanding the basic structure of a Node.js program.
File I/O: Create a Node.js script that reads the contents of a file and outputs it to the console. This will help you understand how to work with the file system in Node.js.
HTTP Server: Create a simple HTTP server in Node.js that listens on a specified port and returns a message to the client. This will help you understand how to create and configure an HTTP server in Node.js.
REST API: Create a simple REST API in Node.js that accepts HTTP requests and returns JSON data. This will help you understand how to create a REST API using Node.js and how to handle HTTP requests and responses.
Express Web Server: Create a web server using the Express framework that serves a static HTML page. This will help you get started with using the Express framework and serving static files in Node.js.
1)
console.log('Hello World');
This script simply outputs "Hello World" to the console using the console.log method. You can run this script using the node command in the terminal.
These exercises are meant to be simple and straightforward, but they can still help you get started with learning Node.js and building basic applications. As you become more familiar with Node.js, you can start working on more complex projects and exploring additional features and modules.
2)
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
In this example, the fs module is imported, which provides file system-related functions. The fs.readFile method is used to read the contents of the file example.txt. The utf8 argument specifies that the file should be read as a UTF-8 encoded file. The err and data parameters are passed to the callback function, which is executed once the file has been read.
If there is an error reading the file, the error will be passed to the err parameter and the if (err) throw err statement will cause an error to be thrown. If the file is read successfully, the contents of the file will be passed to the data parameter and will be logged to the console using console.log(data).
This example demonstrates how to read the contents of a file in Node.js using the fs module and the fs.readFile method. You can modify this code to read different types of files or to perform different operations with the file contents.
3)
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}/`);
});
In this example, the http module is imported, which provides the basic functionality for creating HTTP servers in Node.js. The http.createServer method is used to create a new HTTP server, which takes a callback function as an argument. The callback function is executed whenever a client makes a request to the server.
The res object represents the HTTP response that will be sent to the client, and the res.statusCode, res.setHeader, and res.end methods are used to configure the response. The res.statusCode method sets the HTTP status code for the response, the res.setHeader method sets the Content-Type header to text/plain, and the res.end method sends the response body with the message "Hello World".
The server.listen method is used to start the server and listen on the specified port and hostname. A callback function is provided that logs a message indicating that the server is running at http://127.0.0.1:3000/.
This example demonstrates how to create a simple HTTP server in Node.js and how to respond to client requests with a message. You can modify this code to create more complex HTTP servers or to serve different types of content to clients.
4)
const express = require('express');
const app = express();
const port = 3000;
app.get('/data', (req, res) => {
res.json({ message: 'Hello World' });
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
In this example, the express module is imported, which provides the Express framework, which makes it easy to create web applications in Node.js.
The express function is called to create a new Express application, which is stored in the app variable. The app.get method is used to handle HTTP GET requests to the /data endpoint. The callback function is executed whenever a client makes a GET request to /data.
The res.json method is used to send a JSON response to the client. In this case, an object with a message property is returned, which has the value "Hello World".
The app.listen method is used to start the Express application and listen on the specified port. A callback function is provided that logs a message indicating that the server is running on the specified port.
This example demonstrates how to create a simple REST API in Node.js using the Express framework and how to handle HTTP requests and return JSON data. You can modify this code to create more complex REST APIs or to return different types of data to clients.
5)
To serve an HTML file using the web server created in the previous exercise, you need to create a directory to store your static files and configure the web server to serve files from that directory. Here's how you can do this:
Create a directory for your static files:
mkdir public
Create an HTML file in the public directory:
cd public
nano index.html
Copy and paste the HTML code from the previous example into the index.html file:
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
</head>
<body>
<h1>Hello World</h1>
<p>Welcome to my web page.</p>
</body>
</html>
Save the file and exit the editor.
Modify the web server code to serve static files from the public directory:
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Start the web server:
node index.js
In this example, the express and path modules are imported. The express module provides the Express framework, which makes it easy to create web applications in Node.js. The path module provides utilities for working with file and directory paths.
The express function is called to create a new Express application, which is stored in the app variable. The app.use method is used to configure the Express application to serve static files. The express.static method is used to specify the directory that contains the static files, which is public in this example.
The app.listen method is used to start the Express application and listen on the specified port. A callback function is provided that logs a message indicating that the server is running on the specified port.
This example demonstrates how to create a web server using the Express framework in Node.js and how to serve static files to clients. You can modify this code to create more complex web applications or to serve different types of content to clients.