When I tried to call up to 200,000 POST requests in NodeJS, it display some errors like heap memory leak.
In each POST request, I want to insert the resolved data into localhost mongo DB.
It's ok to make 2000 requests at one time but it's really difficult to deal with 200,000 requests. I got stuck in this problem and don't know exactly to resolve it.
I really need your help or any suggestions.
Thank you in advance for your help.
const mongoose = require('mongoose');
const request = require('request');
// DB connection
mongoose
.connect("mongodb://localhost:27017/test?retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected!'))
.catch(err => console.error('Could not connect...', err));
// Initialize Mongoose 's model
const Sample = mongoose.model(
'Sample',
new mongoose.Schema({}, { strict: false, versionKey: false }),
'sample_collection'
);
// Insert data into Sample
var insertDataIntoSample = function (means) {
Sample.collection.insert(means, { ordered: false });
}
// HTTP POST request to get data
const getDataFromInternet = function (param) {
return new Promise((resolve, reject) => {
request.post(
'https://url-to-post-data.com/',
{ json: { 'query': param } },
function (error, response, body) {
if (!error && response.statusCode == 200 && body) {
insertDataIntoSample(body.data);
resolve(param);
}
}
);
});
};
// Call up to 200,000 requests
var myParams = [...] // 200,000 elements
for (var i = 0; i < myParams.length; i++) {
getDataFromInternet(myParams[i]).then(function (data) {
console.log(data)
})
}