Creating an entire user data submission and file-writing mechanism without any external libraries on the server-side, including the notable exclusion of Express and fs-extra, involves utilizing only native Node.js modules such as http for serving the web page and handling HTTP requests, and fs for file system operations. Below is an example of how you might accomplish this task with basic functionality.
Step 1: HTML & JavaScript for User Information Form
The index.html file remains largely the same. Save this with your other project files.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Collect User Info</title>
</head>
<body>
<h2>User Information Form</h2>
<form id="userInfoForm">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="phone">Phone:</label><br>
<input type="text" id="phone" name="phone"><br><br>
<input type="button" value="Submit" onclick="submitForm()">
</form>
<script>
function submitForm() {
const name = document.getElementById('name').value;
const phone = document.getElementById('phone').value;
if (!name || !phone) {
alert('Both name and phone are required!');
return;
}
const userData = { name, phone };
fetch('/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData),
})
.then(response => response.json())
.then(data => {
alert('User data submitted successfully!');
})
.catch((error) => {
alert('Error:', error);
});
}
</script>
</body>
</html>
Step 2: Node.js Server without Outside Libraries
You'll create a simple HTTP server that serves the HTML file and handles POST requests to store user data.
// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const usersFilePath = path.join(__dirname, 'users.json');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
fs.readFile(path.join(__dirname, 'index.html'), (err, data) => {
if (err) {
res.writeHead(500);
res.end('Server Error');
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
});
} else if (req.method === 'POST' && req.url === '/submit') {
let body = '';
req.on('data', chunk => {
body += chunk.toString(); // convert Buffer to string
});
req.on('end', () => {
const userData = JSON.parse(body);
// Read existing users.json file or start fresh
let existingUsers = [];
if (fs.existsSync(usersFilePath)) {
const rawData = fs.readFileSync(usersFilePath);
const data = JSON.parse(rawData);
existingUsers = data.users;
}
// Add new user and write to file
existingUsers.push(userData);
fs.writeFileSync(usersFilePath, JSON.stringify({ users: existingUsers }, null, 2), 'utf8');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'User data saved!' }));
});
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
Running Your Application:
- Ensure
index.html and server.js are in the same directory.
- Run the server using Node.js by executing
node server.js.
- Open a browser and go to
http://localhost:3000/ to see the user form.
- Submitting the form will save the data to
users.json in the same directory as your server script.
This example demonstrates a simple way to handle HTTP requests without external libraries, meeting the criteria of not using any outside library. Remember, this is a very basic setup; real-world applications often require more robust handling, validation, and security measures.