Advertisement
jargon

Roe2Js :: "files.js"

Jun 26th, 2024
666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function loadJSONSync(url) {
  2.    
  3.     url = fixURL(url);
  4.    
  5.     var xhr = new XMLHttpRequest();
  6.    
  7.     xhr.open('GET', url, false); // 'false' makes the request synchronous
  8.    
  9.     xhr.send(null);
  10.    
  11.     if (xhr.status === 200) {
  12.        
  13.         return JSON.parse(xhr.responseText);
  14.        
  15.     } else {
  16.        
  17.         // throw new Error('Failed to load JSON');
  18.         return [];
  19.        
  20.     }
  21. }
  22.  
  23. function loadJSONDirect (url) {
  24.    
  25.     url = fixURL ( url );
  26.    
  27.     if( !fileExists ( url ) ) {
  28.         return [];
  29.     }
  30.    
  31.     try {
  32.         var data = loadJSONSync(url);
  33.         // // console.log(data);
  34.     } catch (error) {
  35.         return [];
  36.         // console.error(error);
  37.     }
  38.     // console.log  ( basename(url), data );
  39.     return data;
  40. }
  41.  
  42. function fileExists ( url ) {
  43.    
  44.     url = fixURL( url );
  45.    
  46.     try {
  47.         fetch ( url );
  48.     } catch (error) {
  49.         return false;
  50.     }
  51.     return true;
  52. }
  53.  
  54. function basename(path = '', ext = '') {
  55.     // Ensure path is a string
  56.     path = path.toString();
  57.  
  58.     // Split the path by '/'
  59.     let parts = path.split('/');
  60.    
  61.     // Get the last part of the path
  62.     let base = parts[parts.length - 1];
  63.    
  64.     // If an extension is specified and the base ends with that extension
  65.     if (ext && right(base, len(ext)) === ext) {
  66.         // Remove the extension from the base
  67.         base = left(base, len(base) - len(ext));
  68.     }
  69.    
  70.     return base;
  71. }
  72.  
  73. function fixURL ( url ) {
  74.  
  75.     // Ensure the URL starts with the host
  76.     if ( !url.startsWith( host ) ) {
  77.         url = `${host}${url}`;
  78.     }
  79.            
  80.     // Replace spaces with %20
  81.     url = url.replace(/ /g, '%20');
  82.  
  83.     return url;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement