const fs = require('fs');
const { Readable } = require('stream');
/**
* Streams data from a dataset file with rate limiting.
* @param {string} filePath Path to the dataset file.
* @param {number} rateLimit Tokens per second.
* @returns {Readable} A Readable stream for the data.
*/
function streamDataset(filePath, rateLimit) {
return new Readable({
read() {
// Simulate reading data from a file. Replace with actual file reading.
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error("Error reading file:", err);
process.exit(1); // Exit on error
}
const chunk = data; //Read the whole file
this.push(chunk);
// Rate limiting: Simulate a delay to respect rate limit.
const delay = 1000 / rateLimit; // milliseconds
const timeout = new Promise(resolve => setTimeout(resolve, delay));
timeout.then(() => {
this.read(); // Request more data
});
});
},
close() {
console.log("Stream closed.");
}
});
}
// Example Usage:
// const filePath = 'your_dataset.txt'; // Replace with your file path
// const rateLimit = 10; // 10 tokens per second
// streamDataset(filePath, rateLimit)
// .pipe(process.stdout); // Pipe to console or other destination
Add your comment