// Step 1: Import the 'fs' (file system) module
const fs = require('fs');
// Step 2: Define the file path
const filePath = 'example.txt';
// Step 3: Create a function to write data to the file
function writeToFile() {
// Generate a random number as content
const content = Math.random();
// Use the 'fs' module to write content to the file
fs.writeFile(filePath, content, (err) => {
if (err) {
console.error('Error writing to file:', err);
} else {
console.log('Content written to file successfully.');
}
});
}
// Step 4: Set up an interval using setInterval
const intervalId = setInterval(writeToFile, 5000);
// Step 5: Stop the interval after a specified time (e.g., 30 seconds)
setTimeout(() => {
clearInterval(intervalId);
console.log('Interval stopped after 30 seconds.');
}, 30000);