Skip to content

Instantly share code, notes, and snippets.

@shirooo39
Last active September 2, 2022 12:10
Show Gist options
  • Save shirooo39/6f8fe563fa68e4c7e89691df531d9dda to your computer and use it in GitHub Desktop.
Save shirooo39/6f8fe563fa68e4c7e89691df531d9dda to your computer and use it in GitHub Desktop.
need help converting this python script to javascript
import pathlib
import requests
import sys
def main():
source = 'https://s4.anilist.co/file/anilistcdn/media/anime/banner/109287-Du3UxrOnIS4w.jpg'
fallback_source = 'D:/test.png'
try:
# check if the given source is a url and image can be pulled from url, but don't actually download the file
requests.get(source)
except requests.exceptions.RequestException:
# if nothing can't be pulled from the given url, check if the given source is a local file path
if not (pathlib.Path(source).exists and pathlib.Path(source).is_file()):
# if nothing can't be find locally, use a fallback source, which is a local file that must present
source = fallback_source
# if fallback source can't be find, print out an html <img> element with empty source
if not (pathlib.Path(source).exists and pathlib.Path(source).is_file()):
sys.exit(f'<img src="" alt="alternate">')
sys.exit(f'<img src="{source}" alt="alternate">')
if __name__ == '__main__':
main()
@shirooo39
Copy link
Author

converted using an online converter but I don't think this is correct...

import * as pathlib from 'pathlib';
import * as requests from 'requests';
import * as sys from 'sys';

function main() {
  var fallback_source, source;
  source = "https://s4.anilist.co/file/anilistcdn/media/anime/banner/109287-Du3UxrOnIS4w.jpg";
  fallback_source = "D:/test.png";

  try {
    requests.get(source);
  } catch (e) {
    if (e instanceof requests.exceptions.RequestException) {
      if (!(new pathlib.Path(source).exists && new pathlib.Path(source).is_file())) {
        source = fallback_source;

        if (!(new pathlib.Path(source).exists && new pathlib.Path(source).is_file())) {
          sys.exit(`<img src="" alt="alternate">`);
        }
      }
    } else {
      throw e;
    }
  }

  sys.exit(`<img src="${source}" alt="alternate">`);
}

if (__name__ === "__main__") {
  main();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment