piston/api/src/helpers.js

33 lines
812 B
JavaScript
Raw Normal View History

2021-02-20 23:39:03 +01:00
const fs = require('fs/promises'),
path= require('path'),
fetch = require('node-fetch'),
urlp = require('url');
2021-02-20 15:13:56 +01:00
module.exports = {
async buffer_from_url(url){
2021-02-20 15:13:56 +01:00
if(!(url instanceof URL))
2021-02-20 23:39:03 +01:00
url = new URL(url);
if(url.protocol == 'file:'){
2021-02-20 15:13:56 +01:00
//eslint-disable-next-line snakecasejs/snakecasejs
2021-02-20 23:39:03 +01:00
return await fs.read_file(urlp.fileURLToPath(url));
2021-02-20 15:13:56 +01:00
}else{
return await fetch({
url: url.toString()
2021-02-20 23:39:03 +01:00
});
2021-02-20 15:13:56 +01:00
}
},
add_url_base_if_required(url, base){
try{
2021-02-20 23:39:03 +01:00
return new URL(url);
2021-02-20 15:13:56 +01:00
}catch{
//Assume this is a file name
2021-02-20 23:39:03 +01:00
return new URL(url, base + '/');
2021-02-20 15:13:56 +01:00
}
},
url_basename(url){
2021-02-20 23:39:03 +01:00
return path.basename(url.pathname);
2021-02-20 15:13:56 +01:00
},
2021-02-20 23:39:03 +01:00
};