1. const fs = require('fs');
  2. const { Readable } = require('stream');
  3. /**
  4. * Streams data from a dataset file with rate limiting.
  5. * @param {string} filePath Path to the dataset file.
  6. * @param {number} rateLimit Tokens per second.
  7. * @returns {Readable} A Readable stream for the data.
  8. */
  9. function streamDataset(filePath, rateLimit) {
  10. return new Readable({
  11. read() {
  12. // Simulate reading data from a file. Replace with actual file reading.
  13. fs.readFile(filePath, 'utf8', (err, data) => {
  14. if (err) {
  15. console.error("Error reading file:", err);
  16. process.exit(1); // Exit on error
  17. }
  18. const chunk = data; //Read the whole file
  19. this.push(chunk);
  20. // Rate limiting: Simulate a delay to respect rate limit.
  21. const delay = 1000 / rateLimit; // milliseconds
  22. const timeout = new Promise(resolve => setTimeout(resolve, delay));
  23. timeout.then(() => {
  24. this.read(); // Request more data
  25. });
  26. });
  27. },
  28. close() {
  29. console.log("Stream closed.");
  30. }
  31. });
  32. }
  33. // Example Usage:
  34. // const filePath = 'your_dataset.txt'; // Replace with your file path
  35. // const rateLimit = 10; // 10 tokens per second
  36. // streamDataset(filePath, rateLimit)
  37. // .pipe(process.stdout); // Pipe to console or other destination

Add your comment