JavaScript google-spreadsheet API logging not working properly - javascript

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.

Related

Github pages, how to fetch file in js from repo

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

How can I check if uploaded and downloaded file have same content with cypress?

I wanted to test if the content of the uploaded file and the downloaded file are the same. So, following is what I tried through cypress:
it.only(cfg.testname, () => {
// 1. Login to website, navigate to desired webapge
// 2. Upload the file
// 3. Download the file
// cy.wait(5000)
// 4. Read the uploaded file:
const fileContent = cy.fixture(_filePath)
console.log('fixture file path', '======>', _filePath)
console.log('fixture file content', '=====>', fileContent)
// 5. Read the downloaded file:
const downloadsFolder = Cypress.config("downloadsFolder")
const downloadedFileContent = cy.readFile(path.join(downloadsFolder, _fileName))
console.log('downloaded file path', '======>', path.join(downloadsFolder, fileName))
console.log('downloaded file content','====>', downloadedFileContent)
// 6. Check if they are equal:
expect(downloadedFileContent).equals(fileContent)
})
However, when I run this test, it does not even complete login step and immediately give asserition error one step 6, that is on expect()...:
AssertionError: expected { Object (userInvocationStack, specWindow, ...) } to equal {
Object (userInvocationStack, specWindow, ...) }
at Context.eval (VM753 tests:224)
When I comment step 6 expect()..., it correctly logins, uploads file and downloads file. So, I felt somehow I should make the process wait till download is complete before expect().... So I tried uncommenting cy.wait(5000), but no help. It still gives me above error (with of course expect()... uncommented).
Q1. Why this behavior?
Q2. How should I fix this?
PS: I am getting bunch of errors in the console which I am unable to understand. This is the screenshot of console:
The fixture read is async, so you need to use .then(), same with cy.readFile()
The use of path.join(downloadsFolder, _fileName) probably will not work as it's a Node command, substitute a string template instead
If you have a complicated file in JSON format, also try .to.deep.eq
cy.fixture(_filePath).then(fileContent => {
const downloadsFolder = Cypress.config("downloadsFolder")
const downloadPath = `${downloadsFolder}/${_fileName}`
cy.readFile(downloadPath).then(downloadedFileContent => {
expect(downloadedFileContent).equals(fileContent)
// or may need deep
// expect(downloadedFileContent).to.deep.eq(fileContent)
})
})

Save spreadsheet row data to PDF using Gdoc template using Google Apps Script

I've exhausted all resources I'm aware of. Watched several different tutorials and spent many hours trying to make this code work.
I'm trying to automatically create a PDF from a spreadsheet row. I save copies of code at every successful run. However, I can't figure out at which point i'm triggering this error:
TypeError: Cannot read property 'makeCopy' of undefined (line 35, file "CreatePDF")
I was able to run the CreatePDF function successfully when defining the variables with "let" but since trying to pull them from the spreadsheet with the function: createbulkpdfs I haven't been able to progress.
Can anyone point me in the right direction? Line 35 noted below**
//doc id 1rFkh5AmLPNAJ7z1olWBvubn-6Oh8S8_my-AML1lU48I
//temp folder 12ZEXitbgdyOQJiC-pHvshgsBuNOKEKpj
//pdf folder 1eomwcc_UNJhFhvxcoWwamyJUterZtTaB
//let name = "Dan";
//let email = "daniel.sgalia#gmail.com";
//let cost = "100";
//let squarefeet = "2000";
//let flooringmaterial = "Wood";
//let roofingmaterial = "Standing Seam";
//let sidingmaterial = "Lap";
//let kitchencounter = "Granite";
function createbulkpdfs(){
const docfile = DriveApp.getFileById("1rFkh5AmLPNAJ7z1olWBvubn-6Oh8S8_my-AML1lU48I");
const tempfolder = DriveApp.getFolderById("12ZEXitbgdyOQJiC-pHvshgsBuNOKEKpj");
const pdffolder = DriveApp.getFolderById("1eomwcc_UNJhFhvxcoWwamyJUterZtTaB");
const currentsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SFR Calculations");
const data = currentsheet.getRange(2, 1,currentsheet.getLastRow()-1,15).getValues();
data.forEach(row => {
createPDF(row[0],email,cost,squarefeet,flooringmaterial,roofingmaterial,sidingmaterial,kitchencounter,pdfname,docfile,tempfolder,pdffolder)
});
}
function createPDF(name,email,cost,squarefeet,flooringmaterial,roofingmaterial,sidingmaterial,kitchencounter,pdfname,docfile,tempfolder,pdffolder) {
**LINE 35** const tempfile = docfile.makeCopy(tempfolder);
const tempdocfile =DocumentApp.openById(tempfile.getId());
const body = tempdocfile.getBody();
body.replaceText("{Name}", name);
body.replaceText("{Email}", email);
body.replaceText("{Cost Estimate}", cost);
body.replaceText("{Square Feet}", squarefeet);
body.replaceText("{Flooring Material}", flooringmaterial);
body.replaceText("{Roofing Material}", roofingmaterial);
body.replaceText("{Siding Material}", sidingmaterial);
body.replaceText("{Kitchen Counter}", kitchencounter);
tempdocfile.saveAndClose();
const pdfcontentblob = tempfile.getAs(MimeType.PDF);
pdffolder.createFile(pdfcontentblob).setName("pdfname");
tempfolder.removeFile(tempfile)
}
Not sure if you worked this out already, but I think the solution might be super simple...
Before you run the script, change it so you are running the function 'CreateBulkPDFs' not 'Create PDF'.
You have two functions in your script, you need to use the drop down at the top next to the Run button to ensure you are running the function 'CreateBulkPDFs'.
If you try to run 'Create PDF' the consts are not defined.
That error would throw because something isn't defined properly. At a glance it looks like because on line 35 you reference 'docfile' and 'tempfolder' which are not defined in the createPDF() function. (They are defined in the previous function)
It's not clear to be why you have the two functions and why you need createPDF to reference the other one, but it appears if you defined 'docfile' and 'tempfolder' (or any var or const that is needed in that function) within createPDF() specifically then it should run.
This should technically answer you question of why the error is happening on that line currently, without going into the full scope of needs for your project.

Run a JavaScript script when excel file trigger an action

I'm using puppeteer to automate some processes, one of them that i want to open an excel file reading the data inside and search the web using this data (open google-->search using the cell's data).
I can do this correctly using Java script, but i want to know if i can run puppeteer when an excel trigger occurs?
because i don't want this to happen randomly i want it to happen when a specific event occurs inside excel sheet.
I've been searching for a while and i couldn't find useful resource. I found https://learn.microsoft.com/en-us/javascript/api/excel/excel.worksheet?view=excel-js-preview#onchanged
but it didn't help me alot as i couldn't understand how to use it.
example:
I have an excel file containing only 1 cell {facbook}. So i was
wondering if there is a way that allows me to run a [java script
script through cmd - that controls puppeteer] when i set another cell on excel to
be = {open}. So whenever a cell CHANGES it's value in excel sheet this
triggers the script i have.
You can use exceljs from node js
const puppeteer = require('puppeteer');
var Excel = require('exceljs');
//reading test.xlsx
wb.xlsx.readFile('test.xlsx').then(function(){
sh = wb.getWorksheet("sheet1");
start_page(sh);
});
//running new browser
async function start_page(sh){
var i = 2;
const browser = await puppeteer.launch({headless: false});
while(i <= sh.rowCount){
var result_cell = sh.getRow(i).getCell(3).text;
await open_page(browser, result_cell);
i ++;
}
}
async function open_page(browser, result_cell) {
const page = await browser.newPage();
page.setDefaultNavigationTimeout(10000);
await page.goto('testurl', {
waitUntil: 'networkidle2'
});
your code here
page.close();
}
Those are the sample code I have done for another project. You can check it with those code.

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()));
}

Categories

Resources