send data from a file to frontend nodejs
Step 1: Import Required Modules
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
Step 2: Read File Data
app.get('/get-file-data', (req, res) => {
const filePath = path.join(__dirname, 'data.txt');
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(err);
res.status(500).send('Error reading the file');
} else {
res.send(data);
}
});
});
Step 3: Start the Server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});