I getting a bit confuse about how to make post request one after one and not use up the server resource. I am trying to re-structure a huge amount of data and post it one by one to a new Mongoose database, I am using a mac pro to serve the gateway. Following are some of my code:
http.get(option, (res) => {
res.on('data', function (chunk) {
str += chunk;
});
res.on('end', async function() {
var data = [];
data = await JSON.parse(str);
*// code is sucessfully till here, all data is received and parse properly*
data.forEach(item => {
var newData = item;
// console.log(newData);
postData(dataCat, newData);
// console.log(item);
})
// console.log(str);
});
str = "";
});
function postData(dataCat, newData) {
// option = 'http://localhost:3008/pbapi/' + dataCat;
// console.log(newData);
var post_options = {
host: '192.168.1.155',
port: '3008',
path: '/pbapi/' + dataCat,
method: 'POST',
headers: {
'Content-Type': 'application/JSON'
}
};
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('end', function (chunk) {
console.log('Response: ' + chunk);
});
});
post_req.write(newData);
post_req.end();
}
** postData() is tested for single JSON object The forEach loop only work when the length of the data is below 2000(I only tested success till 2000 and failed at 2500).
Error code: 'ENFILE' If i put 2500 and above for the forEach loop