JavaScript https get request - javascript

a get request to the address https://api.steampowered.com/ISteamApps/GetAppList/v2/?format=json is sent too long with this code:
https.get("https://api.steampowered.com/ISteamApps/GetAppList/v2/?format=json", (res) =>
{
res.setEncoding("utf8");
let bodyCount = "";
res.on("data", (dataCount) => {
bodyCount += dataCount;
});
res.on("end", () => {
bodyCount = JSON.parse(bodyCount);
console.log(bodyCount);
});
});
The process takes up to several seconds, so how to make it happen faster?

In case anyone is wondering how I solved the problem:
setInterval(() =>{
https.get("https://api.steampowered.com/ISteamApps/GetAppList/v2/?format=json", (res) => {
res.setEncoding("utf8");
let body ="";
res.on("data", (dataCount) => {
body += dataCount;
});
res.on("end", () =>{
fs.writeFile('./steamdatabase.txt', body, (err) => {
if (err) {
console.error(err)
return
}
});
});
});
}, 86400000);
...
fs.readFile('./steamdatabase.txt', (err, data) => {
if (err) {
console.error(err)
return
}
let body = JSON.parse(data);
for(let i = 0;i<body.applist.apps.length;i++){
if(body.applist.apps[i].name == generateParameter(args)) appidGame = body.applist.apps[i].appid;
}
if(appidGame) appInfo(appidGame,mess);
});

Related

Extract matching row by comparing two CSV file in NodeJs

The scenario is I have two large CSV files csv1.csv and csv2.csv. In both the files, there is an email column and I have to read csv1.csv row by row and check if the email exists in csv2.csv and if matches write the row of csv2.csv in csv3.csv. I have tried read stream as well but it is not working as expected. Any guidance or help is appreciated.
Thanks to all in advance.
Following are the CSV files
csv1.csv
email,header1,header2
test1#example.com,test1,test1
test2#example.com,test2,test2
test3#example.com,test3,test3
test4#example.com,test4,test4
test5#example.com,test5,test5
csv2.csv
email,header1,header2
test4#example.com,test4,test4
test5#example.com,test5,test5
test6#example.com,test6,test6
test7#example.com,test7,test7
test8#example.com,test8,test8
Following is the code that I tried
const fs = require('fs');
const csv = require('fast-csv')
class CsvHelper {
static write(filestream, rows, options) {
return new Promise((res, rej) => {
csv.writeToStream(filestream, rows, options)
.on('error', err => rej(err))
.on('finish', () => res());
});
}
constructor(opts) {
this.headers = opts.headers;
this.path = opts.path;
this.writeOpts = {
headers: this.headers,
includeEndRowDelimeter: true
};
}
create(rows) {
return CsvHelper.write(fs.createWriteStream(this.path, { flags: 'a' }), rows, { ...this.writeOpts });
}
append(rows) {
return CsvHelper.write(fs.createWriteStream(this.path, { flags: 'a' }), rows, {
...this.writeOpts,
writeHeaders: false,
});
}
}
class Helper {
async matchCsv (outerRow) {
try {
const filePath2 = "csv2.csv";
const filePath3 = "csv3.csv";
let row = [];
const csvFile = new CsvHelper({
path: filePath3,
headers: ["Email", "Active"]
});
return new Promise((resolve, reject) => {
fs.createReadStream(filePath2)
.on("error", err => {
reject(err);
})
.pipe(csv.parse({headers: true}))
.on("error", err => {
reject(err);
})
.on("data", async innerRow => {
if(outerRow["email"] === innerRow["email"]) {
console.log("====================");
console.log("match found");
console.log(innerRow);
console.log("====================");
row.push([innerRow["email"], "yes"]);
console.log("row: ", row);
}
})
.on("finish", async() => {
if (!fs.existsSync(filePath3)) {
await csvFile.create(row).then(() => {
resolve("Done from matchCsv");
})
} else {
await csvFile.append(row).then(() => {
resolve("Done from matchCsv");
})
}
})
});
} catch (err) {
throw(err);
}
}
async generateCsv () {
try {
const filePath1 = "csv1.csv";
return new Promise((resolve, reject) => {
fs.createReadStream(filePath1)
.on("error", err => {
reject(err);
})
.pipe(csv.parse({headers: true}))
.on("error", err => {
reject(err);
})
.on("data", async outerRow => {
const result = await this.matchCsv(outerRow);
console.log("result: ", result);
})
.on("finish", () => {
resolve("Generated csv3.csv file.");
});
});
} catch (err) {
throw(err);
}
}
}
async function main() {
const helper = new Helper();
const result = await helper.generateCsv()
console.log(result);
}
main();
So the question is a little confusing, but I think I know what you want. Here's what I would do to check if the email exists. It will add all the rows to an array, cycle through them, then if the email address matches the email you're looking for, it will do something else... I think you said you wanted to write to a csv file again with the row, but that should be simple enough.
const csv = require('csv-parser');
const fs = require('fs');
const filepath = "./example_data.csv";
const emailAdd = "myemail#email.com";
var rowsArr = [];
fs.createReadStream(filepath)
.on('error', () => {
// handle error
})
.pipe(csv())
.on('data', (row) => {
rowsArr.push(row);
})
.on('end', () => {
for (var i = 0; i <= rowsArr.length; i++) {
if (rowsArr[i].emailAddress == emailAdd) {
//do something
}
}
})

how to handle proxy error in core-https in node js

so am using core-https to do a Get request to a webstie , iam doing this get reqeust using a proxy by using this code :
const { HttpsProxyAgent } = require("https-proxy-agent");
const proxy = new HttpsProxyAgent(`http://user:pass#host:port`);
https.get("https://www.google.com/",
{ agent: proxy },
(res) => {
var body = "";
res.on("data", function (chunk) {
body += chunk;
// console.log(body)
});
res.on("end", function () {
}
);
})
so sometimes the proxy would be invalid or expired , or even use a local-host for debugging using fiddler or Charles
const { HttpsProxyAgent } = require("https-proxy-agent");
const proxy = new HttpsProxyAgent(`http://127.0.0.1:8888`); // For Debugging
https.get("https://www.google.com/",
{ agent: proxy },
(res) => {
var body = "";
res.on("data", function (chunk) {
body += chunk;
// console.log(body)
});
res.on("end", function () {
}
);
})
and would also result an error if i forgot to open a proxy-debugger .
i tried doing it in this way :
res.on("error" , function(e){
console.log("an error have been occurred ")
})
but nothing seems to work
So i found the answer , it would be done like this
https.get(
"https://www.google.com/",
{ agent: proxy },
(res) => {
var body = "";
res.on("data", function (chunk) {
body += chunk;
});
res.on("end", function () {
// console.log(body)
})
.on('error', function (e) {
console.error("error");
}).end();

Node js pause while loop wait until functions inside get executed completely?

I am coding a post request which downloads all URL HTML,zips them and email it back. This all should happen in the backend. I am storing all the data in an array and extract the first element to start these operations.
I have while loop inside which I am calling some functions. Each function gets executed at a certain time.
I used async, await and promises to make sure they run one after the
other.
Coming to my problem.
My while loop starts getting executed again before all the
functions inside it are executed.
app.post('/?', async (req, res) => {
var urls = req.query.urls
var email = req.query.email;
var new_stack = [urls, email]
stack.push(new_stack)
res.send("Mail sent")
if (isFunctionRunning === false) { //initially it is false
console.log(isFunctionRunning, stack.length)
send_mails();
}
});
const getGoogleIndexHTML = (url) => {
return new Promise((resolve, reject) => {
request(url, (err, res, body) => err ? reject(err) : resolve(body))
})
}
const some_function_to_download = async (url) => {
try {
const a = url.split(".")
let googleIndexHTML = await getGoogleIndexHTML(url)
await fs.writeFile(directory + '/' + a[1] + '.html', googleIndexHTML, (err) => {
if (err) throw err
})
console.log('File created.')
} catch (err) {
console.log(err)
}
}
const html_to_zip_file = async () => {
await zipper.zip(directory, function (error, zipped) {
if (!error) {
zipped.compress();
zipped.save('./package.zip', function (error) {
if (!error) {
console.log("Saved successfully !");
}
});
} else {
console.log(error)
}
})
}
const send_mails = async () => {
while (stack.length > 0) {
isFunctionRunning = true
var a = stack.shift()
var urls = a[0]
var collection_urls = urls.split(",");
var to_email = a[1]
rimraf(directory, function () {
console.log("done");
});
fs.mkdirSync(directory);
for (url of collection_urls) {
await some_function_to_download(url); // 5 sec per download
}
await html_to_zip_file() // takes 5 sec to zip
.then(result => {
transporter.sendMail(set_mail_options(to_email)) //2 sec to send mail
.then(result => {
console.log("Mail sent")
})
.catch(err => {
console.log(err)
})
})
.catch(err => {
console.log(err)
})
console.log("reached") // this is reached before zip is done and mail sent. I want to prevent this
}
isFunctionRunning = false
}
You need to return transporter.sendMail in sendMail, fs.writeFile in someFunctionToDownload and zipper.zip in htmlToZipFile otherwise the await won't work as expected (I'm assuming that they actually do return promises, I'm only familiar with fs.writeFile)
Also: CamelCase is used in JS, not snake_case 🙃
And are you sure rimraf is synchronous?
const sendMails = async () => {
while (stack.length > 0) {
isFunctionRunning = true;
const [urls, toEmail] = stack.shift();
var collectionUrls = urls.split(",");
rimraf(directory, function() {
console.log("done");
});
await fs.mkdir(directory);
await Promise.All(collectionUrls.map(someFunctionToDownload)); // 5 sec per download
await htmlToZipFile() // takes 5 sec to zip
.then(result => transporter.sendMail(set_mail_options(toEmail))) //2 sec to send mail
.then(result => {
console.log("Mail sent");
})
.catch(err => {
console.log(err);
});
console.log("reached"); // this is reached before zip is done and mail sent. I want to prevent this
}
isFunctionRunning = false;
};
const someFunctionToDownload = async url => {
const a = url.split(".");
const googleIndexHTML = await getGoogleIndexHTML(url);
return fs.writeFile(`${directory}/${a[1]}.html`, googleIndexHTML, err => {
if (err) throw err;
});
};
const htmlToZipFile = async () => {
return zipper.zip(directory, function(error, zipped) {
if (!error) {
zipped.compress();
zipped.save("./package.zip", function(error) {
if (!error) {
console.log("Saved successfully!");
}
});
} else {
console.log(error);
}
});
};
Try using the following
while (stack.length > 0) {
isFunctionRunning = true
var a = stack.shift()
var urls = a[0]
var collection_urls = urls.split(",");
var to_email = a[1]
rimraf(directory, function () {
console.log("done");
});
fs.mkdirSync(directory);
for (url of collection_urls) {
await some_function_to_download(url); // 5 sec per download
}
try {
const result = await html_to_zip_file() // takes 5 sec to zip
const sendMailResult = await transporter.sendMail(set_mail_options(to_email))
} catch(e)
{
console.log(e)
}
console.log("reached")
}
Since html_to_zip_file() and sendMail function are independent
we can use
const result = await Promise.all([html_to_zip_file(),transporter.sendMail(set_mail_options(to_email))]);

How to make sequence of commands for questionnaire in Telegram bot?

For a questionary, I have over 80 questions in the following code I tied to do that but was not working. I will be appreciated for any help:
I am using telegraf SDK for bot:
Question e.g :
1)Q1: Seldom I am feeling good. (1 point)
Q2: I am feeling good always. (2 points)
app.action('Start', (ctx) => {
//console.log(getdata('http://localhost:3000/api/questions'));
getdata(myCallback);
});
var myCallback = function (data) {
let i = Object.keys(data).length;
let x = 0;
for (x = 0;x!=i; x++ ){
app.action(ctx => {
ctx.editMessageText('Choose your own proper sentence:', Extra.HTML().markup(m => m.inlineKeyboard([
m.callbackButton(data[x].Q1, 'plus1'),
m.callbackButton(data[x].Q2, 'plus2')
])))
});
}
};
app.action('pluse1',(ctx)=>{
console.log(1);
//do somethings
});
app.action('pluse2', (ctx) => {
console.log(2);
//do other things
});
var getdata = function (callback) {
http.get('http://localhost:3000/api/questions', (res) => {
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
callback(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
}
function callback(data){
console.log('cb',data)
this.qa = data;
}

streaming from large files and creating an array

I'm having problems with highland.js. I need to create an array of functions from my stream data, but can't get it to work. Here's my code, however requests is always empty.
var requests = [];
_(fs.createReadStream("small.txt", { encoding: 'utf8' }))
.splitBy('-----BEGIN-----\n')
.splitBy('\n-----END-----\n')
.filter(chunk => chunk !== '')
.each(function (x) {
requests.push(function (next) {
Helpers.Authenticate()
.then(function (response1) {
return Helpers.Retrieve();
})
.then(function (response2) {
return Helpers.Retrieve();
})
.then(function () {
next();
});
});
});
console.log(requests)
async.series(requests);
Just read highland's doc. Try adding .done to your stream and console.log out the requests.
_(fs.createReadStream("small.txt", { encoding: 'utf8' }))
.splitBy('-----BEGIN-----\n')
.splitBy('\n-----END-----\n')
.filter(chunk => chunk !== '')
.each(function (x) {
requests.push(function (next) {
Helpers.Authenticate()
.then(function (response1) {
return Helpers.Retrieve();
})
.then(function (response2) {
return Helpers.Retrieve();
})
.then(function () {
next();
});
});
}).done(function(){
console.log(requests);
});
I would just use the stream events to wire things up:
var stream = fs.createReadStream('small.txt', {encoding: "utf8"});
stream.on('data', (line) => {
var lineStr = line.toString(); //Buffer to String
/* You code here */
})
stream.on('close', (line) => {
console.log(request);
})

Categories