The goal is to call a function from my main script that connects to a database, reads a document from it, stores pieces of that document in a new object, and returns that object to my main script. The problem is I cannot get it all to work together. If I try one thing, I get the results but my program locks up. If I try something else I get undefined results.
Long story short, how do I open a database and retrieve something from it to another script.
The program is a quiz site and I want to return the quiz name and the questions.
const myDb = require('./app.js');
var myData = myDb.fun((myData) => {
console.log(myData.quizName);
});
Here is the script that tries to open the database and find the data
const { MongoClient } = require("mongodb");
const {mongoClient} = require("mongodb");
const uri = connection uri goes here but my name is hard coded into it at the moment so I removed for privacy
const client = new MongoClient(uri);
const fun = async (cback) => {
try {
await client.connect();
const database = client.db('Quiz-Capstone');
const quizzes = database.collection('Quiz');
const query = {quizName: "CIS01"};
const options = {
sort: {},
projection: {}
};
const quiz = await quizzes.findOne(query, options);
var quizObject = {
quizName: quiz.quizName,
quizQuestions: quiz.quizQuestions
}
//console.log(testOb);
} finally {
await client.close();
cback(quizObject);
}
}
fun().catch(console.dir);
module.exports = {
fun: fun
}
UPDATE: Still stuck. I have read several different threads here about asynchronous calls and callbacks but I cannot get my function located in one file to return a value to the caller located in another file.
I saved data on workbook on following code
export const storeSettingsToWorkbook = async (settingsType: Settings, storeData:
WorkbookModel) => {
return Excel.run(async (context) => {
const originalXml = createXmlObject(storeData);
const customXmlPart = context.workbook.customXmlParts.add(originalXml);
customXmlPart.load("id");
await context.sync();
// Store the XML part's ID in a setting
const settings = context.workbook.settings;
settings.add(settingsTitles[settingsType], customXmlPart.id);
await context.sync();
})
}
when i get data -it works normally.But when i want to get this data form another "add-in" on Excel- I cannot get this data
const {settings} = context.workbook;
const sheet = context.workbook.worksheets.getActiveWorksheet().load("items");
const xmlPartIDSetting = settings.getItemOrNullObject(settingsTitles[settingsType]).load("value");
await context.sync();
if (xmlPartIDSetting.value) {
const customXmlPart = context.workbook.customXmlParts.getItem(xmlPartIDSetting.value);
const xmlBlob = customXmlPart.getXml();
await context.sync()
const parsedObject = parseFromXmlString(xmlBlob.value);
const normalizedData = normalizeParsedData(parsedObject);
Any ideas?
Thanks for reaching us.
This is by design. Each addin has its own setting and cannot share with each other.
You can use 'context.workbook.properties.custom' as a workaround.
You can also use 'context.workbook.worksheets.getActiveWorksheet().customProperties', but the two add-ins are required to be on the same worksheet.
I'm using the azure file storage, and using express JS to write a backend to render the contents stored in the azure file storage.
I am writing the code based on https://learn.microsoft.com/en-us/javascript/api/#azure/storage-file-share/shareserviceclient?view=azure-node-latest
const { ShareServiceClient, StorageSharedKeyCredential } = require("#azure/storage-file-share");
const account = "<account>";
const accountKey = "<accountkey>";
const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
`https://${account}.file.core.windows.net`,
credential
);
const shareName = "<share name>";
const fileName = "<file name>";
// [Node.js only] A helper method used to read a Node.js readable stream into a Buffer
async function streamToBuffer(readableStream) {
return new Promise((resolve, reject) => {
const chunks = [];
readableStream.on("data", (data) => {
chunks.push(data instanceof Buffer ? data : Buffer.from(data));
});
readableStream.on("end", () => {
resolve(Buffer.concat(chunks));
});
readableStream.on("error", reject);
});
}
And you can view the contents through
const downloadFileResponse = await fileClient.download();
const output = await streamToBuffer(downloadFileResponse.readableStreamBody)).toString()
Thing is, I only want to find if the file exists and not spend time downloading the entire file, how could I do this?
I looked at https://learn.microsoft.com/en-us/javascript/api/#azure/storage-file-share/shareserviceclient?view=azure-node-latest
to see if the file client class has what I want, but it doesn't seem to have methods useful for this.
If you are using #azure/storage-file-share (version 12.x) Node package, there's an exists method in ShareFileClient. You can use that to find if a file exists or not. Something like:
const fileExists = await fileClient.exists();//returns true or false.
I'm developing an AWS Lambda in TypeScript that uses Axios to get data from an API and that data will be filtered and be put into a dynamoDb.
The code looks as follows:
export {};
const axios = require("axios");
const AWS = require('aws-sdk');
exports.handler = async (event: any) => {
const shuttleDB = new AWS.DynamoDB.DocumentClient();
const startDate = "2021-08-16";
const endDate = "2021-08-16";
const startTime = "16:00:00";
const endTime = "17:00:00";
const response = await axios.post('URL', {
data:{
"von": startDate+"T"+startTime,
"bis": endDate+"T"+endTime
}}, {
headers: {
'x-rs-api-key': KEY
}
}
);
const params = response.data.data;
const putPromise = params.map(async(elem: object) => {
delete elem.feat1;
delete elem.feat2;
delete elem.feat3;
delete elem.feat4;
delete elem.feat5;
const paramsDynamoDB = {
TableName: String(process.env.TABLE_NAME),
Item: elem
}
shuttleDB.put(paramsDynamoDB).promise();
});
await Promise.all(putPromise);
};
This all works kind of fine. If the test button gets pushed the first time, everything seems fine and is working. E.g. I received all the console.logs during developing but the data is not put into the db.
With the second try it is the same output but the data is successfully put into the Db.
Any ideas regarding this issue? How can I solve this problem and have the data put into the Db after the first try?
Thanks in advance!
you need to return the promise from the db call -
return shuttleDB.put(paramsDynamoDB).promise();
also, Promise.all will complete early if any call fails (compared to Promise.allSettled), so it may be worth logging out any errors that may be happening too.
Better still, take a look at transactWrite - https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#transactWrite-property to ensure all or nothing gets written
I have a json file that is generated dynamically by taking the values of a page using a crawler, json is created as follows:
{
"temperatura":"31°C",
"sensacao":"RealFeel® 36°",
"chuva":"0 mm",
"vento":"NNO11km/h",
"momentoAtualizacao":"Dia",
"Cidade":"carazinho",
"Site":"Accuweather"
}
{
"temperatura":"29 º",
"sensacao":"29º ST",
"vento":"11 Km/h",
"umidade":"51% UR",
"pressao":"1013 hPa",
"Cidade":"carazinho",
"Site":"Tempo Agora"
}
The problem with this generated file is missing [] to join all the files inside an array, and commas to separate the files.
The final json should look like this:
[{
"temperatura":"31°C",
"sensacao":"RealFeel® 36°",
"chuva":"0 mm",
"vento":"NNO11km/h",
"momentoAtualizacao":"Dia",
"Cidade":"carazinho",
"Site":"Accuweather"
},
{
"temperatura":"29 º",
"sensacao":"29º ST",
"vento":"11 Km/h",
"umidade":"51% UR",
"pressao":"1013 hPa",
"Cidade":"carazinho",
"Site":"Tempo Agora"
}]
I am currently using this code to generate json.
const climatempo = async (config) => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
const override = Object.assign(page.viewport(), {width: 1920, heigth:1024});
await page.setViewport(override);
await page.goto(config.cidades[cidade],{waitUntil: 'load',timeout:'60000'})
if(siteEscolhido == "accu"){
const elementTemp = await page.$(config.regras.elementTemp)
const temperatura = await page.evaluate(elementTemp => elementTemp.textContent, elementTemp)
const sensacaoElement= await page.$(config.regras.sensacaoElement)
const sensacao = await page.evaluate(sensacaoElement => sensacaoElement.textContent, sensacaoElement)
const chuvaElement = await page.$(config.regras.chuvaElement)
const chuva = await page.evaluate(chuvaElement => chuvaElement.textContent, chuvaElement)
const ventoElement = await page.$(config.regras.ventoElement)
const vento = await page.evaluate(ventoElement => ventoElement.textContent, ventoElement)
const atualizadoA = await page.$(config.regras.atualizadoA)
const momentoAtualizacao = await page.evaluate(atualizadoA => atualizadoA.textContent, atualizadoA)
var dado = {
temperatura:temperatura,
sensacao:sensacao,
chuva:chuva,
vento:vento,
momentoAtualizacao:momentoAtualizacao,
Cidade:cidade,
Site:"Accuweather"
}
//dados.push(dado)
var x = JSON.stringify(dado)
fs.appendFile('climatempo.json',x,function(err){
if(err) throw err
})
console.log("Temperatura:" + temperatura)
console.log(sensacao)
console.log("Vento:" + vento)
console.log("chuva:" + chuva)
console.log(momentoAtualizacao)
await browser.close()
If anyone has any idea how to solve my problem, please let me know!
Grateful, Carlos
I would suggest doing it a little differently
I will try to explain in pseudo code since i dont understand your variable names
read json file
array = JSON.parse(fileContents)
array.push(newItem)
newContents = JSON.stringify(array)
file WRITE (not append) newContents
I recommend reading the file, pushing onto an array captured from that file, and then writing the file back to disk.
Assuming the file has content already in the form of an array:
let fileDado = JSON.parse(fs.readFileSync('climatempo.json'));
fileDado.push(dado);
fs.writeFileSync('climatempo.json', JSON.stringify(fileDado));