Github pages, how to fetch file in js from repo - javascript

I have a github pages project that I am trying to create. I've got it working great on local, but of course when I publish it it fails.
The problem is in this bit of javascript, which is supposed to pull some data from a json file in the repo to build the contents of a certain page:
(async function(){
const response = await fetch(`https://GITUSER.github.io/GITREPO/tree/gh-pages/data/file.json`);//Error gets thrown here, because the asset does not exist in the current code state.
const docData = await response.json();
const contentTarget = document.getElementById('doc-target');
const tocTarget = document.getElementById('toc-target')
createContent(tocTarget,contentTarget,docData);
})();
Now, the problem is that pages won't load the asset because it doesn't know that it needs it until the function is called. Is there a way to get this asset loaded by pages so it can be called by the fetch API? Or is this beyond the capabilities of github pages?
Edited: Added some additional code for context.

Try using raw.githubusercontent.com like this
(async function(){
const response = await fetch('https://raw.githubusercontent.com/{username}/{repo}/{branch}/{file}')
const docData = await response.json();
const contentTarget = document.getElementById('doc-target');
const tocTarget = document.getElementById('toc-target')
createContent(tocTarget,contentTarget,docData);
})();
And it would work

Related

JavaScript google-spreadsheet API logging not working properly

I am a beginner at Javascript.
Trying to read data from GoogleSheets using google-spreadsheet API(https://www.npmjs.com/package/google-spreadsheet)
For some reason, console.log is not working in below code.
Also, I am getting all the google sheet info printed in the console, which is so much that I am not able to see the full log.
const { GoogleSpreadsheet } = require("google-spreadsheet");
const doc = new GoogleSpreadsheet("****************-*******-*******");
const serviceAccountCreds = require("./serviceAccountCredentials.json");
let expenseSheet;
// Load envs in process
process.env["GOOGLE_SERVICE_ACCOUNT_EMAIL"] = serviceAccountCreds.client_email;
process.env["GOOGLE_PRIVATE_KEY"] = serviceAccountCreds.private_key;
// authenticate to the google sheet
const authenticate = async () => {
await doc.useServiceAccountAuth({
client_email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
private_key: process.env.GOOGLE_PRIVATE_KEY,
});
};
authenticate();
//load Spreadsheet doc info
const docInfo = async () => {
await doc.loadInfo(); // loads document properties and worksheets
console.log(doc.title); // This line does not seem to work
};
docInfo();
I am requiring help with 2 things.
The console.log does not seem to print anything.
The Google sheet information is getting printed, which I don't want it to be.
Thanks in advance.
To check the console.log, I tried to output console log to a file, by using the below command in windows.
nodejs readSheet.js > path_to_file
Even though the file is generated, there is no log in that file.

Trying to call a function on Uniswap V2 Factory contract on local ganache eth fork, instead getting error that I have no access to archive state

I am trying to call a simple view function allPairsLength() in a JS script using Truffle but I am getting the following error on running the script: Error: Returned error: project ID does not have access to archive state.
Here is the code:
const V2FACTORY = "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f";
const V2PAIR = "0x3356c9A8f40F8E9C1d192A4347A76D18243fABC5";
const V2ROUTER2 = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D";
const V3QUOTER = "0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6";
const Ifactory = artifacts.require("UniswapV2Factory");
const IPairV2 = artifacts.require("UniswapV2Pair");
const IRouter02V2 = artifacts.require("UniswapV2Router02");
const IQuoter = artifacts.require("Quoter");
module.exports = async function getNoOfPairs() {
let instance = await Ifactory.at(V2FACTORY);
let numberOfPairs = await instance.allPairsLength();
console.log(numberOfPairs);
};
Could someone please point me in the right direction? Thanks a lot!
I see from your comment that you forked a public network using Infura provider.
Infura provides only a limited number of past blocks. Currently about 200 blocks. So if you fork the network at block 1000, and the current block becomes 1200, they won't provide you with any more data as it's over the limit.
Solution: Just reinit the local fork, so that it's forked from a newer block.

listRef.listAll() function is undefined (react-native-firebase)

I am trying to get the list of images in a directory from firebase storage.
Example I want to get all image in users/userid/images, but it does not work and popup an error which the function is undefined.
const listRef = storageRef.child('users/userid/images');
listRef.listAll().then(res=>{
res.items.forEach(itemRef=>{
// console.log(itemRef);
});
}).catch(e =>{});
The ability to list files in a storage bucket wasn't added until version 6.1.0 of the JavaScript SDK. So make sure your SDK is up to date.
And now we can do it as well, thnk you from react-native-firebase team.
const reference = storage().ref('images');
const getListOfImages = async (){
const res = await reference.child('profileimages').list();
return await Promise.all(res.items.map(i => i.getDownloadURL()));
}

Can't load all of the page content with phantom

I just wanted to let you know that i ve tried the solution with setTimeout (before marking my question as DUPLICATE)
The problem is related to the website that i'm scraping
So when i used phantomJs it only scrape the first part of the web page and not all of the page
I even tried another webscraping tool (APIFY) and it returns the same content
This is the page that i'm scraping the page that i want to scrape
And this is the code that i'm using :
var phantom = require("phantom");
(async function() {
const instance = await phantom.create();
const page = await instance.createPage();
await page.on("onResourceRequested", function(requestData) {
console.info("Requesting", requestData.url);
});
const status = await page.open(
"https://www.articles-epresse.fr/media/894eab75-c642-46a2-a1ba-b240c278ebbc?"
);
const content = await page.property("content");
console.log(content);
var $ = cheerio.load(content);
console.log($("#article319670").attr("href")); // returns undefined
//because phantomJs is not reaching the end of the page
await instance.exit();
})();
PS : i used phantom because the code source of the page is not the same as " inspect element"
Thank You

How to play a sound from JS in a UWP app?

I'm developing a UWP that contains a WebApp that has some JS functions that invokes some C# functions. Nowadays, I'm trying to play a sound that I have stored in the Assets folder of my UWP app:
This is the function that I'm trying to play of my Windows Runtime Component:
public async void Beep()
{
await CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
async () =>
{
MediaElement mysong = new MediaElement();
StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");
StorageFolder soundsFolder = await folder.GetFolderAsync("sounds");
StorageFile file = await soundsFolder.GetFileAsync("beep.mp3");
var stream = await file.OpenAsync(FileAccessMode.Read);
mysong.SetSource(stream, file.ContentType);
mysong.Play();
});
}
By the way, I also tried this code and it didn't work too:
public async void Beep()
{
MediaElement mysong = new MediaElement();
StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");
StorageFolder soundsFolder = await folder.GetFolderAsync("sounds");
StorageFile file = await soundsFolder.GetFileAsync("beep.mp3");
var stream = await file.OpenAsync(FileAccessMode.Read);
mysong.SetSource(stream, file.ContentType);
mysong.Play();
}
This is the structure of the location of the file:
And this is how I'm calling it from JS:
CallJSCSharp.Beep();
I have more functions inside the Windows Runtime Component and all of them are working as expected with exception of this one. Thanks for your help.
MediaElement needs to be added to a XAML UI tree to work; you should just use the MediaPlayer API instead. You don't even need to write C# code to do it - you should be able to access the API directly from JavaScript (if you want to). More on the Media Playback overview page
I found how to fix it:
I added both projects in the same solution:
UWP project.
Windows Runtime Component.
I removed extra code from the function (it's unnecessary to add the Media Element in the XAML as suggested before).
public async void Beep()
{
MediaElement mysong = new MediaElement();
StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");
StorageFolder soundsFolder = await folder.GetFolderAsync("sounds");
StorageFile file = await soundsFolder.GetFileAsync("beep.mp3");
var stream = await file.OpenAsync(FileAccessMode.Read);
mysong.SetSource(stream, file.ContentType);
mysong.Play();
}
Important to remember when you call any JS function, it must be with lower cases because JS conventions (even if your function has been written with upper cases).
CallJSCSharp.beep();
More information about JS Conventions:
Using the Windows Runtime in JavaScript

Categories

Resources