stream-multiple.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. var needle = require('needle');
  2. const fs = require('fs-extra')
  3. function stream_multiple(req, res, _urls, stream_dir, index = 0) {
  4. if (index == 0) {
  5. // initial state
  6. }
  7. let writeStream;
  8. const uri = _urls[index];
  9. if (index == undefined) {
  10. index = 0;
  11. stream_multiple(req, res, _urls, stream_dir, index);
  12. } else {
  13. writeStream = fs.createWriteStream(`${stream_dir}` + `${index}.jpeg`);
  14. writeStream.on("ready", () => console.log({ msg: `STREAM::WRITE::READY::${index}` }));
  15. writeStream.on("open", () => console.log({ msg: `STREAM::WRITE::OPEN::${index}` }));
  16. writeStream.on("finish", () => console.log({ msg: `STREAM::WRITE::DONE::${index}` }));
  17. writeStream.on('close', () => {
  18. if (index >= _urls.length - 1) {
  19. res.redirect('/');
  20. } else {
  21. stream_multiple(req, res, _urls, stream_dir, index + 1);
  22. }
  23. })
  24. needle
  25. .get(uri, function (error, response) {
  26. if (response.bytes >= 1) {
  27. // you want to kill our servers
  28. }
  29. if (!error && response.statusCode == 200) {
  30. // good
  31. } else {
  32. // then we can retry later
  33. }
  34. })
  35. .pipe(writeStream)
  36. .on('done', function () {
  37. // needle
  38. });
  39. }
  40. }
  41. module.exports = { stream_multiple }