Sending multiple JSON request to server under one request nodejs - json

I have some files downloaded and I wanna push them to a server. Every time I try to push the file I get the error
Error: Can't set headers after they are sent.
I have a for loop that reads all the files and parse them and after that I want to send them to the server one by one.
app.get('/dataparser', function(req, res) {
var fs = require('fs');
var obj;
var jsonGis = new Array();
var jsonArray;
var filePaths = [];
const downloadFolder = './sampletest/';
var mtimes = {};
var reloadTimes = 10000;
fs.readdir(downloadFolder, (err, files) => {
files.forEach(file => {
filePaths.push("sampletest/" + file);
});
})
var execFunction = function() {
for (var i = 0; i < filePaths.length; i++) {
parseFile(filePaths[i], mtimes[filePaths[i]]);
}
};
execFunction();
setInterval(execFunction, reloadTimes);
function parseFile(fileName, lastModifiedTime) {
fs.stat(fileName, function(err, fd) {
for (var i=0, len = filePaths.length; i<len; i++) {
if (fd.mtime !== lastModifiedTime) {
mtimes[fileName] = fd.mtime;
fs.readFile(filePaths[i], function(err, data) {
if (err) {
return console.error(err);
}
obj = JSON.parse(data);
jsonGis.push('"Person1"');
jsonGis.push('"' + obj.pages[1].answers[2].values[0] + '"');
jsonGis.push('"person2"');
jsonGis.push('"' + obj.pages[1].answers[0].values[0] + '"');
jsonGis.push('"codewals"');
jsonGis.push('"42343GSDS"');
jsonGis.push('"geometry":{');
jsonGis.push('"x":' + obj.pages[1].answers[4].values[0].coordinates.latitude + ',');
jsonGis.push('"y":' + obj.pages[1].answers[4].values[0].coordinates.longitude);
var str = "[{ " + jsonGis[0] + jsonGis[1] + jsonGis[2] + ": " + jsonGis[3] + "," + jsonGis[4] + ": " + jsonGis[16] + "}}]"
//pushing to the server
console.log("check here");
console.log(str);
var qs = require("querystring");
var http = require("http");
var options = {
"method": "POST",
"hostname": "twst2.gtw.com",
"port": null,
"path": "localpath/",
"headers": {
"accept": "application/json",
"content-type": "application/x-www-form-urlencoded",
}
};
var req = http.request(options, function(res) {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
res.on("end", function() {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(qs.stringify({features: str}));
res.send("The server was updated");
req.end();
});
}
}
});
};
Just need to send the data to the server from file1.json and then file2.json then file3.json and so on.

Try creating a separate callback function that includes .write, .send, and .end, then let it be the callback for .request.

Related

JSON Call from view to controller and show JSON object data in view in ASP.NET Core 6 MVC

I have written code in an ASP.NET Core 6 controller and calling this from view. This code gives response to my view but I don't know how to parse the data in view.
Previously I was using JsonrequestBehaviour.Allowget which is now deprecated in .NET 6. Please help me for better appraoch of json call which can return any dynamic object.
Here is my controller code:
public IActionResult GetAccountLevelAndCode(Int32 GroupAccountID, Int32 Companyid)
{
string AccountLevels = ""; string Returnerror; string ReturnBranches;
DataTable AL = new GetDataClass().GetAccountNoAndAndLevels(GroupAccountID, Companyid, out Returnerror);
//a = (GLChartOFAccountModel)AL.Rows[0].ConvertDataRowToObject(a);
string Sql = #"select cab.BranchID from GLChartOFAccount ca inner join GLChartOfAccountBranchDetail cab on ca.GLCAID=cab.GLCAID where cab.GLCAID=" + GroupAccountID;
DataTable dt = new DataTable();
dt = StaticClass.SelectAll(Sql).Tables[0];
AccountLevels = JsonConvert.SerializeObject(AL);
ReturnBranches = JsonConvert.SerializeObject(dt);
Returnerror = JsonConvert.SerializeObject(Returnerror);
return Json(new { AccountLevels, ReturnBranches, Returnerror });
}
Following is my view call and response allocation:
function GetAccountNoandLevel() {
var DATA={"GroupAccountID" : $('#isParent').val(), Companyid : #Model.CompanyID }
var execCode = true;
$.ajax({
async: false,
type: "POST",
url: "/GLChartOFAccount/GetAccountLevelAndCode",
data: DATA,
dataType: "json",
success: function (data) {
try {
var c = JSON.parse(data.AccountLevels)
var b = JSON.parse(data.ReturnBranches)
var er = JSON.parse(data.Returnerror)
if (b.length>0) {
$("#BrachIDs option").each(function () {
var idParent = $(this).parent().attr("id");
this.disabled = true;
});
var dataarray = '';
for (var i = 0; i < b.length; i++) {
dataarray += b[i]["BranchID"] + ',';
}
dataarray = dataarray.replace(/,\s*$/, "");
var data = dataarray.split(",");
$("#BrachIDs").val(data);
$("#BrachIDs").change();
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
$("#BrachIDs option").filter("[value='" + data[i] + "']").attr('disabled', false);
}
}
}
else {
$("#BrachIDs option").each(function () {
var idParent = $(this).parent().attr("id");
this.disabled = false;
});
$("#BrachIDs option:selected").removeAttr("selected");
}
if (ShowErrorOK(er)) {
$('#GLCode').val('');
}else{
RowToFillValues(c)
}
} catch (e) {
//console.log(e + " GetAccountNoandLevel "); document.getElementById("DisplayErrorMessage").innerText = e.message; $('#btnTriggerMessage').click(); execCode = false; return false;
console.log(e + " GetAccountNoandLevel "); console.log(e.message)
}
},
error: function (err) {
//console.log(err.responseText); document.getElementById("DisplayErrorMessage").innerText = "AJAX error in request: " + JSON.stringify(err.statusText + " " + err.status) + " GetAccountNoandLevel::Unable To Get Details"; $('#btnTriggerMessage').click(); execCode = false; return false;
console.log("AJAX error in request: " + JSON.stringify(err.statusText + " " + err.status) + " GetAccountNoandLevel::Unable To Get Details")
}
});
if (execCode) {
}
}
The response data is showing undefined...
you don't need serialize and parse manually, it will be done automaticaly
return new JsonResult(new { AccountLevels=AL, ReturnBranches=dt, Returnerror= Returnerror });
and ajax
var c = data.AccountLevels;
var b = data.ReturnBranches;
var er = data.Returnerror;

Why my Node.Js code not giving response in first request while taking value from user?

In this code, I am sending a POST request to the server which contains email-id and using that email-id I am retrieving Information from the database.
I am testing this from postman "http://127.0.0.1:80/echo" POST request after sending a request first time it shows in response
{
"source": "webhook-echo-sample"
}
and the second time it gives me proper result
{
"speech": "Name:xyz Mobile.no:123456789Address:qweCollege:azx Email:cvb#gmail.com",
"source": "webhook-echo-sample"
}
Why my first request to API is going fail?
"use strict";
const express = require("express");
const restService = express();
const bodyParser = require("body-parser");
const os = require('os');
var mysql = require("mysql");
var final;
var Name = "Name:";
var Mobileno = "Mobile.no:";
var College = "College:";
var Address = "Address:";
var Email = "Email:";
restService.use(
bodyParser.urlencoded({
extended: true
})
);
restService.use(bodyParser.json());
restService.post("/echo", function(req, res) {
var con = mysql.createConnection({
host: "abc.com",
user: "xyz123",
password: "123456",
database: "seller1"
});
var email = req.body.result.parameters.echoText
var sql = 'SELECT * FROM seller1 WHERE email_id=' + mysql.escape(email);
con.query(sql, function(error, results) {
if (!error) {
for (var i = 0; i <= results.length - 1; i++) {
final = Name + results[i].Name + "\n" + Mobileno + results[i].mobile_no + "\n" + Address + results[i].Address + "\n" + College + results[i].College + "\n" + Email + results[i].email_id;
}
} else {
return [];
}
});
return res.json({
"speech": final,
"source": "webhook-echo-sample"
});
});
restService.listen(process.env.PORT || 80, function() {
console.log("Server up and listening");
});
I think it's because of javascript Asynchronous nature
try sending the response inside !error check as shown below
restService.post("/echo", function(req, res) {
var con = mysql.createConnection({
host: "abc.com",
user: "xyz123",
password: "123456",
database: "seller1"
});
var email = req.body.result.parameters.echoText
var sql = 'SELECT * FROM seller1 WHERE email_id=' + mysql.escape(email);
con.query(sql, function(error, results) {
if (!error) {
for (var i = 0; i <= results.length - 1; i++) {
final = Name + results[i].Name + "\n" + Mobileno + results[i].mobile_no + "\n" + Address + results[i].Address + "\n" + College + results[i].College + "\n" + Email + results[i].email_id;
}
return res.json({
"speech": final,
"source": "webhook-echo-sample"
});
} else {
return [];
}
});
});

"Debugging connection was closed: Render process was gone", when trying to download a 7gb from cdn

We are trying to download a 7 GB from CDN using JSZip.js. The chrome browser suddenly seems to close the connection when the download reaches 3.5gb every time. The approximate time is around 15 mins. Is there a way we increase the tolerant time to 1 hr say?
$("#downloadJSZip").on('click', function () {
var result = [{ "cdn": "url....", "filename": "7.84 gb.zip", "size": 4194304, "path": "7.84 gb" }];
var Promise = window.Promise;
if (!Promise) {
Promise = JSZip.external.Promise;
}
function urlToPromise(url) {
return new Promise(function(resolve, reject) {
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
reject(err);
} else {
resolve(data);
}
});
});
}
var fileNameArray = [];
function changeFileName(fileName,j){
var i = fileName.lastIndexOf('.');
var newfilename = fileName.slice(0,i)+"--"+j+fileName.slice(i);
if(fileNameArray.indexOf(newfilename) != -1){
j = j+1;
changeFileName(fileName,j);
}
return newfilename;
}
var zip = new JSZip();
// find every checked item
result.forEach(function(file){
var filename = file.filename;
if(fileNameArray.indexOf(filename) != -1){
var newfilename = changeFileName(filename,1);
filename = newfilename;
}
fileNameArray.push(filename);
var url = file.cdn;
var folder = (file.path);
zip.folder(folder).file(filename, urlToPromise(url), {binary:true});
// zip.file(filename, urlToPromise(url), {binary:true});
});
// when everything has been downloaded, we can trigger the dl
zip.generateAsync({type:"blob",
}, function updateCallback(metadata) {
var msg = "progression : " + metadata.percent.toFixed(2) + " %";
if(metadata.currentFile) {
msg += ", current file = " + metadata.currentFile;
}
console.log(msg);
console.log(metadata.percent|0);
})
.then(function callback(blob) {
// see FileSaver.js
//console.log("blob=====>");
//console.dir(blob);
//saveAs(blob, "example.zip") ;
saveAs(blob, $scope.folderName+".zip") ;
//console.log("done !");
}, function (e) {
});
});
Is this chrome browser configuration?

No output after trying loading data on the fly using Json and ajax

var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = ourRequest.responseText;
renderHTML(ourData);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
pageCounter++;
if (pageCounter > 3) {
btn.classList.add("hide-me");
}
});
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].name + " is a " + data[i].species + "</p>";
}
animalContainer.insertAdjacentHTML('beforeend', htmlString);
}
I have checked every thing and i don't know what is wrong with the code... I am trying to load information on the fly using Json and ajax
You did not parse your data to JSON so what you have to do is parse your "ourData" to JSON.. Remove and add this line of to your code.
var ourData = JSON.parse(ourRequest.responseText);

NodeJS creating JSON using all JSONs uploaded by user

I am trying to make a JSON file using all the JSON files in a directory. Every time a user uploads a new JSON a new combined JSON should be generated. I want the new JSON to have a custom structure hence cant use any libraries. I have the following code:
router.post('/upload', function(req, res) {
var sampleFile;
var bbbid = req.body.bbbid;
DDLFile = req.files.DDLFile;
j++;
DDLFile.mv('/uploads/' + bbbid + '/device' + j + '.json', function (err) {
if (err) {
res.status(500).send(err);
}
else {
res.redirect("fileuploaded");
}
});
var myfiles = [];
var fs = require('fs');
var arrayOfFiles = fs.readdirSync('/uploads/' + bbbid);
arrayOfFiles.forEach(function (file) {
myfiles.push(file);
console.log(myfiles);
});
console.log('No of Files:', myfiles.length);
var files = myfiles.length;
console.log('Files:', files);
console.log('J', j);
var cddl = "{ BBBID:" + bbbid;
if (files == 0) {
cddl = cddl + '}';
console.log('Entered if loop');
}
else {
var i = 0;
/*var obj;
fs.readFile('/uploads/' + bbbid + '/device' + j + '.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
});*/
for (i = 0; i < files; i++) {
console.log('Entered For loop');
console.log('Count:', count);
console.log('Sensor:', sensor);
try{
var obj = fs.readFileSync('/uploads/' + bbbid + '/device' + count + '.json', 'utf8');}
catch(err){
console.log(err);
}
console.log('everything good');
var obj1 = JSON.parse(obj);
console.log('hi');
//JSON.stringify(obj);
var ddl = require('/uploads/' + bbbid + '/device' + count + '.json');
console.log('o');
cddl = cddl + ", {" + obj1.DDL.Sensor.Description.Verbose_Description + ":" + JSON.stringify(ddl) + "}"
JSON.stringify(cddl);
console.log(cddl);
count++;
sensor++;
console.log('Count:', count);
console.log('Sensor:', sensor);
}
cddl = cddl + '}';
JSON.stringify(cddl);
console.log(cddl);
}
});
I want to generate a new cddl everytime a new file is uploaded. Having a lot of problems. Help please!
I see two problems. First instead of this:
var obj = fs.readFileSync('/uploads/' + bbbid + '/device' + count + '.json', 'utf8');}
catch(err){
console.log(err);
}
console.log('everything good');
var obj1 = JSON.parse(obj);
You can write(fix path, if necessary):
var obj1 = require('./uploads/' + bbbid + '/device' + count + '.json')
Then, when you call:
JSON.stringify(cddl);
You're not saving the result anywhere. So you should save it in the place, you need to:
var a = JSON.stringify(cddl);
And when all set, dont forget to write to file back using fs.writeFileSync or async one fs.writeFile.