Why node js express route never stops running - node.js

I have made a route in express and it works below is the code snippet:
In app.js I have added:
var generateOrders = require('./routes/generateOrders');
app.use('/generate-orders', generateOrders);
In generateOrders.js:
var express = require('express');
var router = express.Router();
var generateOrdersServices = require('../services/generateOrders')
router.get('/get-orders', function (req, res) {
generateOrdersServices.getOrders(function (errGenerateOrders, responseGenerateOrders) {
if(errGenerateOrders){
console.log(errGenerateOrders);
res.render(errGenerateOrders);
return;
}
else{
console.log(responseGenerateOrders);
res.render(responseGenerateOrders);
return;
}
})
})
Now when I hit http://localhost:4000/generate-orders/get-orders It does not stop ever.
My code generate a log file, where I add all the input and when I hit this route it keeps on adding output to the log file again and again.Also in terminal everything keeps on printing again and again.
below is my code which I am using to generate a log file for my console output:
/*************************Log Console **********************/
var log_file = fs.createWriteStream(base_log_path+'/getorders/getorders'+year+'-'+month+'-'+day+'-'+hours+'-'+minutes+'-'+seconds+'.log', {flags : 'w'});
var log_stdout = process.stdout;
console.log = function(d) { //
log_file.write(util.format(d) + '\n');
log_stdout.write(util.format(d) + '\n');
};
/*************************Log Console **********************/
Please suggest some solution.
Update
generateOrdersServices.getOrders:
var getOrders = function(callback){
exportedTradeIds(storename,function(err_processedList, tradeIds){
if(err_processedList){
console.log("Error in getting Processed trade ids from exported table error is: "+err);
return callback('Error in getting Processed trade ids from exported table error is: '+err);
}
else if(tradeIds == 0)
{
console.log('No exported trade Ids');
return callback('No exported trade Ids');
}
else
{
jdp_tb_trade.getJstTrades('WAIT_BUYER_CONFIRM_GOODS', 900, 30, 'tmall_i18n', tradeIds, function(err_jdp, jdp_tb_trades){
if(err_jdp)
{
callback('Error in jdp_trade_response. Error is: '+err_jdp);
return;
}
if(!jdp_tb_trades)
{
callback(null, 'No result found from remote database.');
return;
}
else
{
for ( i in jdp_tb_trades) {
if(i == 1)
{
processConsign(jdp_tb_trades[i].tid,
function (err_process_consign, lpnumber) {
if (err_process_consign) {
console.log("Some error occurred in processConsign. Error is:" + err_process_consign);
var jdp_response_json_parsed = JSON.parse(jdp_tb_trades[i].jdp_response);
//Check if generate XML is enabled from admin end.
configuration.getOneByKey('generateXml', function (err_configuration, result_configuration) {
if (err_configuration) {
console.log('[generateXml]: generate xml enabled/disabled - No response.')
}
else
{
if (result_configuration.value == 'true') {
console.log('[generateXml]: generate xml enabled.')
generateXml(jdp_tb_trades[i].tid, jdp_response_json_parsed, lpnumber, function (err_generate_xml, success_generate_xml) {
if (err_generate_xml) {
return callback(err_generate_xml);
}
else {
return callback(null, success_generate_xml);
}
});
}
else{
console.log('[generateXml]: generate xml disabled.');
}
}
});
}
else
{
console.log("response from processConsign:Lpnumber" + lpnumber);
var jdp_response_json_parsed = JSON.parse(jdp_tb_trades[i].jdp_response);
//Check if generate XML is enabled.
configuration.getOneByKey(
'generateXml',
function (err_configuration, result_configuration) {
if (err_configuration) {
console.log('[generateXml]: generate xml enabled/disabled - No response.')
}
else {
if (result_configuration.value == 'true')
{
console.log('[generateXml]: generate xml enabled.')
generateXml(jdp_tb_trades[i].tid, jdp_response_json_parsed, lpnumber, function (err_generate_xml, success_generate_xml) {
if (err_generate_xml)
{
return callback(err_generate_xml);
}
else
{
return callback(null, success_generate_xml);
}
});
}
else
{
console.log('[generateXml]: generate xml disabled.');
}
}
});
}
});
}
}
}
});
}
})
};
module.exports = {
getOrders: function (callback) {
getOrders(function(err_getOrders, getOrdersResponse){
if(err_getOrders){
console.log("generate Order process error:"+err_getOrders);
return callback(err_getOrders);
}
else{
console.log("generate Order process success:"+getOrdersResponse);
return callback(null, getOrdersResponse);
}
});
},
}
I have omitted some code from generateOrdersServices.getOrders as it is not allowed to post that much code here.

Related

Node.js writing data to file throws an error

Got this error when I run my program
TypeError: Callback is not a function
// Update data from a new file
lib.update = function(dir,file,callback){
//Open the file for writing
fs.open(lib.baseDir+dir+'/'+'.json','r+',function(err,fileDescriptor){
if(!err && fileDescriptor){
var stringData= JSON.stringify(data);
//Truncate the file before writing
fs.truncate(fileDescriptor,function(err){
if(!err){
//Write to the file and close it
fs.writeFile(fileDescriptor,stringData,function(err){
if(!err){
fs.close(fileDescriptor,function(err){
if(!err){
callback(false);
}else {
callback('Error closing existing file!')
}
})
}else {
callback('Error writing to existing file')
}
});
}else {
callback('Error Truncating file')
}
});
}else {
callback('Could not open file for updating! May not exist yet')
}
});
}
I propose you to refactor your code to be a little more clear about what you are doing. Something like this, it will help you find where errors come. Using promises better than use a lot of callbacks.
Just my contribution.
lib.update = function(dir, file, data) {
const updateP = new CustomPromise();
openFile()
.then(truncateFile)
.then(writeFile.bind(this, JSON.stringify(data)))
.then(closeFile)
.then(updateP.resolve) // at this point all the functions was successful
.catch((errorType) =>
errorType !== ERROR_TYPE.ERROR_CLOSING_FILE // something fail try to close the file
? closeFile().finally(() => updateP.reject(errorType))
: updateP.reject(errorType),
);
return updateP.promise;
};
// Constants
const ERROR_TYPE = Object.freeze({
ERROR_OPEN_FILE: 'error-open-file',
ERROR_TRUNCATING_FILE: 'error-truncating-file',
ERROR_WRITING_FILE: 'error-writing-file',
ERROR_CLOSING_FILE: 'error-closing-file',
});
// Private functions
function CustomPromise() {
this.promise = new Promise(function(resolve, reject) {
this.resolve = resolve;
this.reject = reject;
});
}
function openFile() {
const openP = new CustomPromise();
fs.open(lib.baseDir + dir + '/' + '.json', 'r+', function(err, fileDescriptor) {
(err || !fileDescriptor) && openP.reject(ERROR_TYPE.ERROR_OPEN_FILE);
openP.resolve(fileDescriptor);
});
return openP.promise;
}
function truncateFile(fileDescriptor) {
const truncateP = new CustomPromise();
fs.truncate(fileDescriptor, function(err) {
err && truncateP.reject(ERROR_TYPE.ERROR_TRUNCATING_FILE);
truncateP.resolve(fileDescriptor);
});
return truncateP.promise;
}
function writeFile(data, fileDescriptor) {
const writeFileP = new CustomPromise();
fs.writeFile(fileDescriptor, data, function(err) {
err && writeFileP.reject(ERROR_TYPE.ERROR_WRITING_FILE);
writeFileP.resolve(fileDescriptor);
});
return writeFileP.promise;
}
function closeFile(fileDescriptor) {
const closeP = new CustomPromise();
fs.close(fileDescriptor, function(err) {
err && closeP.reject(ERROR_TYPE.ERROR_CLOSING_FILE);
closeP.resolve();
});
return closeP.promise;
}

Query is executed later then the return execution expressjs

I have a function that returns a certain json after it executes the query. but that json is coming as default, which i set, but i want the updated values from db.
Code :-
function addPet(pet) {
var body = {
msg : "",
insertId : null
};
console.log(pet.pet_type);
if(pet.pet_type){
mysql.mySqlConnection.query("insert into master_pet(pet_type) values(?)",[pet.pet_type], (err,rows,fields) => {
if(err){
console.log("Query Error :- " + err );
body.msg = "Error While Inserting";
body.insertId = null;
console.log("reached here");
return body;
}
else{
console.log("Inserted" + pet.pet_type);
console.log(rows.insertId);
body.msg = "Inserted Successfully";
body.insertId = rows.insertId;
console.log("reached here");
return body;
}
});
return body;
}
}
Calling Method :-
routes.post('/setPet',(req,res) => {
var pet = req.body;
var body = petmodel.addPet(pet);
res.setHeader('Content-Type', 'application/json');
res.json(body);
});
in here on the client, the json which I am receiving is default one.
Please help.
TIA
function addPet(pet, callback) {
var body = {
msg : "",
insertId : null
};
console.log(pet.pet_type);
if(pet.pet_type){
mysql.mySqlConnection.query("insert into master_pet(pet_type) values(?)",[pet.pet_type], (err,rows,fields) => {
if(err){
console.log("Query Error :- " + err );
body.msg = "Error While Inserting";
body.insertId = null;
console.log("reached here");
}
else{
console.log("Inserted" + pet.pet_type);
console.log(rows.insertId);
body.msg = "Inserted Successfully";
body.insertId = rows.insertId;
console.log("reached here");
}
return callback(body);
});
}
}
--
routes.post('/setPet',(req,res) => {
var pet = req.body;
petmodel.addPet(pet, (body) => {
res.setHeader('Content-Type', 'application/json');
return res.json(body);
});
});

Node FS ENOENT error

I am trying to make this script create a directory, then write stuff in it. Simple XML dumps & stuff.
I cant get anything of FS to work. isDirectory, createDirectory, readFile, writeFile. My reading in another SO post suggested a lot of changes to fs.stat().
I already set the permissions for the folder, so it should not be having any permissions problem (Windows).
My 1st step in checking for previous files & creating new or opening them:
. . .
var logsDir = './logs/';
var logAccess = logsDir + 'stuff.log';
try { // The code says its an ENOENT
console.log(fs.statSync(logsDir))
if (!fs.statSync(logsDir).isDirectory()) {
fs.mkdirSync(logsDir);
}
} catch (e) {
console.error('Error ' + e.code);
}
try { // Another ENOENT
if (!fs.statSync(logAccess).isFile()) {
fs.writeFileSync(logAccess, 'die', 'utf8');
}
//data = fs.readFileSync(logAccess, 'utf8');
} catch (e) {
console.error('Error errors are dumb');
}
. . .
fs.stat(logsDir, function(err,stat){
try{
if(err)
{
var e = err.code;
throw e;
}
}
catch(e)
{
if(e == 'ENOENT')
{
fs.mkdir(logsDir);
}
else
{
console.log('Some other error ' + err.code);
}
}
});
fs.stat(logAccess, function(err,stat){
try{
if(err)
{
var e = err.code;
throw e;
}
}
catch(e)
{
if(e == 'ENOENT')
{
fs.writeFileSync(logAccess, 'die', 'utf8');
}
else
{
console.log('Some other error ' + err.code);
}
}
});
var fs = require('fs');
var express = require("express");
var app = express();
var logsDir = './logs/';
var logAccess = logsDir + 'stuff.log';
function directoryExits(logsDir){
try {
return fs.statSync(logsDir).isDirectory();
} catch (err) {
return false;
}
}
function fileExits(logAccess){
try {
return fs.statSync(logAccess).isFile();
} catch (err) {
return false;
}
}
var statsDir = directoryExits(logsDir);
var statsFile = fileExits(logAccess);
if(!statsDir)
{
fs.mkdirSync(logsDir);
console.log("Directory Created")
}
else
console.log('Directory already exists');
if(!statsFile)
{
fs.writeFileSync(logAccess, 'die', 'utf8');
}
else
console.log('File already exists');
app.listen(4000, function(){
console.log('Server running ');
});

Error: Can't set headers after they are sent in sailsJs Middleware

I am facing an issue where I am trying to set cookie value inside my middleware after some request calls using Bluebird promises, but I am getting error that " Error: Can't set headers after they are sent ",
My Code is
User.autoLogin(req, cookieToken).then(function(apiResponse) {
console.log("Autologin response");
console.log(apiResponse.autologin);
return apiResponse.autologin;
}).then(function(apiResponse) {
if (apiResponse.success === true) {
var returnUser = {};
returnUser = apiResponse.metadata.user;
returnUser.isUser = 1;
returnUser.cartItemsCount = apiResponse.metadata.no_of_items_cart || 0;
returnUser.checkoutStep = 2;
var upSesReq = {
"Al": "1",
"userId": returnUser.id_customer
};
var sessUpdate = User.updateSession(req, upSesReq);
sessUpdate.then(function(sesRes) {
console.log(sesRes);
if (sesRes.success === true) {
req.logIn(returnUser, function (err) {
if (err) {
console.log(err);
forceLogout = true;
logError(err);
} else {
forceLogout = false;
/*
UserEvents.on('loginSuccess', function(req, res){
UserActivityListener.setAutoLoginCookie(req, res);
});
*/
console.log("Auto Login succcessful");
sails.log.verbose("Autologin success full for User");
req.session.totalJabongCredit = returnUser.total_store_credits || 0;
var expirationTime = new Date(Date.now() + (180 * 24 * 60 * 60 * 1000));
res.cookie('xxxx', req.session.token, { expires: expirationTime, httpOnly: true });
autologin = true;
//UserActivityListener.setAutoLoginCookie(req, res);
//UserEvents.loginSuccess(req, res);
}
});
console.log("After login session");
console.log(req.session);
console.log("After login session");
} else {
if (!isEmpty(sesRes.err)) {
logError(sesRes.err);
forceLogout = true;
} else {
logError(sesRes.message);
forceLogout = true;
}
}
}).catch(function(err) {
logError(err);
forceLogout = true;
});
}
}).error(function(err) {
logError(err);
forceLogout = true;
}).catch(function(err) {
logError(err)
forceLogout = true;
});
I am getting error when I am trying to set Cookie. In My autoLogin call I am calling some apis and based in result which is promise object I am going forward. I did not used res.end() in my methods Like AutoLogin. Please let me know what exactly causing this issue?
Looks like something happens in:
var sessUpdate = User.updateSession(req, upSesReq);
It runs in parallel with
sessUpdate.then(function(sesRes) {
.....
}

process.nextTick() Error : Can't set header after they sent error in sails js

![enter image description here][1]
I'm using sailsJs in my application. My server runs properly in my local, but server throws error "process.nextTick() Error : Can't set header after they sent".
Local version is working fine, But server throws above error. And I could not use any setInterval function in application. Don't know why this has happened.
My Controller Code
var lodash = require("lodash");
var FileController = {
upload: function (req, res) {
if(req.method === 'POST'){
console.log('plus button pressed........');
var filenameOriginal;
var carRecordFound=false;
req.file('uploadFile').upload({saveAs: function(file, cb) {
cb(null, file.filename);
filenameOriginal=file.filename;
},
dirname: '../../assets/images'
}, function whenDone(err, uploadedFiles) {
if(req.param('plateNumber')!=undefined){
var originalPlateNumber=req.param('plateNumber');
var updatedPlateNumber=originalPlateNumber.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
if(err){
return res.json(500, err);
}
else if(uploadedFiles.length === 0){
Account.findOne(req.param('accountID')).populateAll().exec(function found(err, accountData){
if (err) return next(err);
if (!accountData) {res.send({notValid : 'notValid'}); return;}
var i=0;
validate(i);
function validate(i){
if(i < accountData.subscriptionLog.length){
//
if(accountData.subscriptionLog[i].subscriptionStatus==undefined){ //SUBSCRIPTION STATUS UNDEFINED STGRTS HERE
console.log(i+'--Subscription is undefined');
i++;
validate(i);
}//SUBSCRIPTION STATUS UNDEFINED ENDS HERE
else if(accountData.subscriptionLog[i].subscriptionStatus=='active'){ //SUBSCRIPTION STATUS ACTIVE STARTS HERE
if(currentDatems<=(accountData.subscriptionLog[i].subscriptionEndDate).getTime()){ //SUBSCRIPTION END DATE VALIDATION STARTS HERE
console.log(i+'--<<uniqueID-------'+accountData.subscriptionLog[i].uniqueID+'Max'+accountData.subscriptionLog.length);
uniqueID=accountData.subscriptionLog[i].uniqueID;
console.log(i+'--<<Strated Processing-------'+accountData.subscriptionLog[i].uniqueID);
Mastertransactional.count({uniqueID : uniqueID}).exec(function countCB(err, found){ //RESPONSE FROM SERVER FOR THE SUBSCRIPTION COUNT
if (err) { console.log('Error------'+err); exitBoolean=true; return next(err); };
if (!found || found==0) {
console.log('No cars parked for this subscription!!!'+found);
}
console.log('There are '+ found +' records founded ');
found1=found;
console.log("numberOfCars-------"+accountData.subscriptionLog[i].numberOfCars);
console.log("found cars-----------"+found1);
if(found1<(accountData.subscriptionLog[i].numberOfCars)){//CAR COUNT VALIDATION STARTS HERE
activeSubscriptionFound=true;
console.log(new Date()+"active condition--------"+activeSubscriptionFound);
console.log('entered into less than car');
if(req.param('parkingID')==undefined || req.param('parkingID')=='' || req.param('plateNumber')=='' || req.param('plateNumber')==undefined )// check empty object from plus button
{
console.log('plus button');
exitBoolean=true;
}
else if(req.param('parkingID')!=undefined || req.param('parkingID')!='')
{
console.log('Car stored');
// ADD THE CAR IN THE DAILY TRANSACTION
Dailytransactional.create(carObj).exec(function(error,carObj){
if(error){console.log('error');}
console.log("daily"+carObj);
Dailytransactional.publishCreate({id: carObj.id,
parkingID: carObj.parkingID,
plateNumber: carObj.plateNumber,
snap: carObj.snap,
parkingZone: carObj.parkingZone,
color: carObj.color,
brand: carObj.brand,
employeeID: carObj.employeeID,
accountID: carObj.accountID,
venue: carObj.venue,
status:carObj.status,
log:carObj.log
});
carObj1['transactionID']=carObj.id;
carObj1['uniqueID']=uniqueID;
Mastertransactional.create(carObj1).exec(function(error,carObj1){
if(error){console.log('error');}
console.log("Master created ---"+carObj1);
exitBoolean=true;
});
});
if((found1+1)==accountData.subscriptionLog[i].numberOfCars){
console.log('Maximum car reached for the subscription');
//CHANGE STATUS OF THE SUBSCRIPTION TO EXPIRED
FileController.subscriptionExpire(req.param('accountID'), accountData.subscriptionLog, i);
}// found +1 if close
}// else if for record insert
console.log('Car Count True Loop Count Incremented');
if(!exitBoolean)
{
i++;
validate(i);
}
}//CAR COUNT VALIDATION ELSE LOOP HERE
else {
FileController.subscriptionExpire(req.param('accountID'), accountData.subscriptionLog, i);
console.log('Car Count Else Loop');
}//CAR COUNT VALIDATION ENDS HERE
console.log(exitBoolean+'After Else Loop >> Counter INcreased'+activeSubscriptionFound);
if(!exitBoolean)
{
i++;
validate(i);
}
if(exitBoolean)
{
if(!activeSubscriptionFound){
//show error message that no active subscription available
console.log(found1+'plus button error called...'+new Date());
res.send({success : 'error'});
return;
}
else
{
console.log(found1+'plus button success'+new Date());
res.send({success : 'success'});
return;
}
}
else
{
console.log(new Date()+'This is the error'+exitBoolean);
}
});// MASTER DATA COUNT FUNCTION ENDS HERE
}// SUBSCRIPTION END DATE VALIDATION ELSE LOOP
else {
FileController.subscriptionExpire(req.param('accountID') ,accountData.subscriptionLog, i);
if(!exitBoolean)
{
i++;
validate(i);
}
} //SUBSCRIPTION END DATE VALIDATION ENDS LOOP
} // SUBSCRIPTION IN LOOP IS NOT ACTIVE
else
{
i++;
console.log(i+'Expired Subscription');
validate(i);
}//SUBSCRIPTION LOOP ENDS HERE
}//MAIN ENTRANCE ENDS HERE
else
{
exitBoolean=true;
if(!activeSubscriptionFound){
console.log(found1+'plus button error'+new Date());
res.send({success : 'error'});
}
}
console.log('coming here<< active subscription--'+activeSubscriptionFound+"--------exitBoolean <<"+exitBoolean);
if(exitBoolean)
{
if(!activeSubscriptionFound){
//show error message that no active subscription available
console.log(found1+'plus button error'+new Date());
//res.send({success : 'error'});
}
else
{
console.log(found1+'plus button success'+new Date());
}
}
else
{
console.log(new Date()+'This is the error'+exitBoolean);
}
}//FUNCTION VALIDATE ENDS HERE
});// account find close
}
else{
// handle uploaded file
}
});
}
},
subscriptionExpire : function(accountID ,subscriptionLog, i) {
var array=[];
array=subscriptionLog;
var subscriptionWantStatus=subscriptionLog[i];
subscriptionWantStatus.subscriptionStatus="Expired";
array.splice(i,1,subscriptionWantStatus);
array.join();
var sLog={
subscriptionLog: array
};
Account.update(accountID,sLog, function venueUpdated(err, car) {
console.log("-Updated log- expired");
});
}
};
module.exports = FileController;
Error throws this code line
console.log(exitBoolean+'After Else Loop >> Counter INcreased'+activeSubscriptionFound); if(!exitBoolean)
{
i++;
validate(i);
}
if(exitBoolean)
{
if(!activeSubscriptionFound){
//show error message that no active subscription available
console.log(found1+'plus button error called...'+new Date());
res.send({success : 'error'});
return;
}
else
{
console.log(found1+'plus button success'+new Date());
res.send({success : 'success'});
return;
}

Resources