javascriptCopy code
// app.js
const express = require('express');
const fs = require('fs');
const exphbs = require('express-handlebars');
const app = express();
const PORT = 3000;
// Middleware to serve static files from the 'public' directory
app.use(express.static('public'));
// Middleware to parse the incoming request body
app.use(express.urlencoded({ extended: true }));
// Set up Handlebars as the view engine
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
// Root route to render the home view
app.get('/', (req, res) => {
res.render('home');
});
// POST route to handle form submissions
app.post('/submit', (req, res) => {
// Construct the output string
const output = `Username: ${req.body.username}, Email: ${req.body.email}\n`;
// Write the output to 'data.txt' file
fs.appendFile('data.txt', output, err => {
// If an error occurs, throw an error
if (err) throw err;
// Send a response back to the client
res.send('Data written to file');
});
});
// Start the server on the defined port
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});