This guide aims to walk beginners and intermediates through creating a simple Node.js server using the http module. The server will handle multiple concurrent requests, simulate asynchronous operations, and implement CORS (Cross-Origin Resource Sharing). Additionally, an optional section demonstrates how to retrieve basic user information (CPU and OS) for a more comprehensive understanding.
Learning Objectives:
- Use the httpmodule to create a Node.js server.
- Handle concurrent requests with non-blocking I/O.
- Simulate asynchronous behavior using random delays.
- Implement CORS to allow requests from different origins (if applicable).
- Retrieve basic user information (CPU and OS) using the osmodule (optional).
Prerequisites:
- Basic understanding of Node.js and JavaScript.
- Node.js and npm (Node Package Manager) installed on your system.
Step-by-Step Guide:
1. Project Setup:
- 
Create a new directory for your project: 
 mkdir node-server cd node-server
- 
Initialize a new npm project: 
 npm init -y
2. Install Dependencies:
- 
We'll need the corspackage to handle CORS:
 npm install cors
3. Create the Server Script:
- Create a file named server.js.
4. Enable CORS (Optional):
- 
By default, the provided code allows CORS for all origins. You can uncomment the following line in server.jsto enable CORS:
 const app = cors();
5. Create the Server:
- 
In server.js, add the following code to create a server using thehttpmodule:
 const http = require('http'); const server = http.createServer((req, res) => { // This function handles incoming requests });
6. Simulate Asynchronous Operation:
- 
Inside the server's request handler function ( server.createServer((req, res) => { ... })), add code to simulate an asynchronous operation using a random delay:
 const delay = Math.random() * 1000; // Delay between 0 and 1 second
7. Respond After Delay:
- 
Use setTimeoutto schedule a response after the delay:
 setTimeout(() => { // Send response to the client here }, delay);
8. Send Response:
- 
Inside the setTimeoutfunction, set the response status code, content type, and send the response message:
 res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Server response after delay!');
9. Specify Port:
- 
Define the port on which the server will listen. You can use an environment variable or a default port: 
 const PORT = process.env.PORT || 8080;
10. Start the Server:
- 
Start the server using server.listenand listen for incoming connections:
 server.listen(PORT, () => { console.log(`Server listening on port ${PORT}`); });
11. Run the Server:
- 
In your terminal, run the following command to start the server: 
 node server.js
12. Test with CORS (Optional):
- If you enabled CORS in step 4, you can test the server from a different domain using tools like Postman or curl.
13. Retrieve User Information (Optional):
- 
You can optionally retrieve basic user information (CPU and OS) using the osmodule. Add the following code toserver.jsafter the delay (setTimeout):
 const os = require('os'); const cpuInfo = os.cpus()[0]; // Get first CPU information const osType = os.type(); // Get OS type const message = `Server response after delay! CPU: ${cpuInfo.model}, OS: ${osType}`;- Update the response message (res.end) to include the retrieved information.
 
- Update the response message (
 
 
              
 
    
Top comments (0)