for appfog I usually use this code:
var host = process.env.VCAP_APP_HOST || "127.0.0.1";
var port = process.env.VCAP_APP_PORT || 1337;
http.createServer(function (req, res) {
// ...
}).listen(port, host);
Now I found a very interesting forum software . Here is the app.js:
'use strict';
/*global global, require, process, module, jsGen, _restConfig*/
var fs = require('fs'),
path = require('path'),
zlib = require('zlib'),
util = require('util'),
http = require('http'),
domain = require('domain'),
serverDm = domain.create(),
processPath = path.dirname(process.argv[1]);
global.jsGen = {}; // 注册全局变量jsGen
jsGen.version = '0.6.6';
serverDm.on('error', function (err) {
delete err.domain;
jsGen.serverlog.error(err);
});
serverDm.run(function () {
jsGen.conf = module.exports.conf = require('./config/config'); // 注册rrestjs配置文件
jsGen.module = {};
jsGen.module.os = require('os');
jsGen.module.xss = require('xss');
jsGen.module.then = require('thenjs');
jsGen.module.marked = require('marked');
jsGen.module.rrestjs = require('rrestjs');
jsGen.module.mongoskin = require('mongoskin');
jsGen.module.nodemailer = require('nodemailer');
jsGen.serverlog = jsGen.module.rrestjs.restlog;
jsGen.lib = {};
jsGen.lib.msg = require('./lib/msg.js');
jsGen.lib.json = require('./lib/json.js');
jsGen.lib.tools = require('./lib/tools.js');
jsGen.lib.email = require('./lib/email.js');
jsGen.lib.redis = require('./lib/redis.js');
jsGen.lib.CacheLRU = require('./lib/cacheLRU.js');
jsGen.lib.converter = require('./lib/anyBaseConverter.js');
jsGen.Err = jsGen.lib.tools.Err;
jsGen.dao = {};
jsGen.dao.db = require('./dao/mongoDao.js').db;
jsGen.dao.tag = require('./dao/tagDao.js');
jsGen.dao.user = require('./dao/userDao.js');
jsGen.dao.index = require('./dao/indexDao.js');
jsGen.dao.article = require('./dao/articleDao.js');
jsGen.dao.message = require('./dao/messageDao.js');
jsGen.dao.collection = require('./dao/collectionDao.js');
jsGen.thenErrLog = function (defer, err) {
jsGen.serverlog.error(err);
};
var redis = jsGen.lib.redis,
then = jsGen.module.then,
each = jsGen.lib.tools.each,
CacheLRU = jsGen.lib.CacheLRU,
extend = jsGen.lib.tools.extend,
resJson = jsGen.lib.tools.resJson,
TimeLimitCache = jsGen.lib.redis.TimeLimitCache;
then(function (defer) {
redis.initConfig(jsGen.lib.json.GlobalConfig, defer); // 初始化config缓存
}).then(function (defer, config) {
jsGen.config = config;
if (!jsGen.config.date) { // config缓存未赋值,则从MongoDB取值
then(function (defer2) {
jsGen.dao.index.getGlobalConfig(defer2);
}).then(function (defer2, config) {
defer2(null, config);
}, function (defer2, err) {
// MongoDB无值,初始化数据库
require('./api/install.js')().then(function () {
defer2(null, jsGen.lib.json.GlobalConfig);
}).fail(defer2);
}).then(function (defer2, config) {
each(jsGen.config, function (value, key, list) {
if (key in config) {
list[key] = config[key]; // 写入config缓存
}
});
defer(null, jsGen.config);
}).fail(defer);
} else {
defer(null, config);
}
}).then(function (defer, config) {
var api = ['index', 'user', 'article', 'tag', 'collection', 'message', 'rebuild'];
jsGen.cache = {};
jsGen.cache.tag = new CacheLRU(config.tagCache);
jsGen.cache.user = new CacheLRU(config.userCache);
jsGen.cache.list = new CacheLRU(config.listCache);
jsGen.cache.article = new CacheLRU(config.articleCache);
jsGen.cache.comment = new CacheLRU(config.commentCache);
jsGen.cache.message = new CacheLRU(config.messageCache);
jsGen.cache.collection = new CacheLRU(config.collectionCache);
jsGen.cache.timeInterval = new TimeLimitCache(config.TimeInterval, 'string', 'interval', false);
jsGen.cache.pagination = new TimeLimitCache(config.paginationCache, 'array', 'pagination', true);
jsGen.robotReg = new RegExp(config.robots || 'Baiduspider|Googlebot|BingBot|Slurp!', 'i');
jsGen.api = {};
each(api, function (x) {
jsGen.api[x] = {}; // 初始化api引用,从而各api内部可提前获取其它api引用
});
each(api, function (x) {
extend(jsGen.api[x], require('./api/' + x + '.js')); // 扩展各api的具体方法
});
fs.readFile(processPath + '/package.json', 'utf8', defer); // 读取软件信息
}).then(function (defer, data) {
data = JSON.parse(data);
data.version = jsGen.version;
data.nodejs = process.versions.node;
data.rrestjs = _restConfig._version;
jsGen.config.info = data;
redis.userCache.index.total(defer); // 读取user缓存
}).then(function (defer, users) {
var rebuild = jsGen.api.rebuild;
if (!users) { // user缓存为空,则判断redis缓存为空,需要初始化
// 初始化redis缓存
then(function (defer2) {
rebuild.user().all(defer2);
}).then(function (defer2) {
rebuild.tag().all(defer2);
}).then(function (defer2) {
rebuild.article().all(defer);
}).fail(defer);
} else {
defer();
}
}).then(function (defer) {
http.createServer(function (req, res) {
var dm = domain.create();
function errHandler(err, res, dm) {
delete err.domain;
try {
res.on('finish', function () {
//jsGen.dao.db.close();
process.nextTick(function () {
dm.dispose();
});
});
if (err.hasOwnProperty('name')) {
res.sendjson(resJson(err));
} else {
jsGen.serverlog.error(err);
res.sendjson(resJson(jsGen.Err(jsGen.lib.msg.MAIN.requestDataErr)));
}
} catch (error) {
delete error.domain;
jsGen.serverlog.error(error);
dm.dispose();
}
}
function router(req, res) {
if (req.path[0] === 'api' && jsGen.api[req.path[1]]) {
jsGen.api[req.path[1]][req.method.toUpperCase()](req, res); // 处理api请求
} else if (req.path[0].toLowerCase() === 'sitemap.xml') {
jsGen.api.article.sitemap(req, res); // 响应搜索引擎sitemap,动态生成
} else if (req.path[0].slice(-3).toLowerCase() === 'txt') {
// 直接响应static目录的txt文件,如robots.txt
then(function (defer) {
fs.readFile(processPath + '/static/' + req.path[0], 'utf8', defer);
}).then(function (defer, txt) {
res.setHeader('Content-Type', 'text/plain');
res.send(txt);
}).fail(res.throwError);
} else if (jsGen.robotReg.test(req.useragent)) {
jsGen.api.article.robot(req, res); // 处理搜索引擎请求
} else {
jsGen.config.visitors = 1; // 访问次数+1
res.setHeader('Content-Type', 'text/html');
if (jsGen.cache.indexTpl) {
res.send(jsGen.cache.indexTpl); // 响应首页index.html
} else {
then(function (defer) {
fs.readFile(processPath + '/static/index.html', 'utf8', defer);
}).then(function (defer, tpl) {
jsGen.cache.indexTpl = tpl.replace(/_jsGenVersion_/g, jsGen.version);
res.send(jsGen.cache.indexTpl);
}).fail(res.throwError);
}
}
}
res.throwError = function (defer, err) { // 处理then.js捕捉的错误
if (!util.isError(err)) {
err = jsGen.Err(err);
}
errHandler(err, res, dm);
};
dm.on('error', function (err) { // 处理domain捕捉的错误
errHandler(err, res, dm);
});
dm.run(function () {
router(req, res); // 运行
});
}).listen(jsGen.module.rrestjs.config.listenPort);
console.log('jsGen start!');
}).fail(function (defer, err) {
throw err;
});
});
Do you know how to modify this code to deploy to appfog?
appfog and cloudfoundry support auto-reconfiguration for node.js applications. So the code should run on AppFog without any modifications.
However if you want to use those environment variables, you can start by modifying the line .listen(jsGen.module.rrestjs.config.listenPort); so it reads:
.listen(process.env.VCAP_APP_PORT, process.env.VCAP_APP_HOST);
Related
I am new to node.js and Javascript.
I have two javascript files "FabricUserController.js" and "UserController.js". So I have create the class in "FabricUserController.js" and export it into "UserController.js".
I am integrate the GetAll fucntion of "FabricUserController.js" to "UserController.js" in GetAllProduce fucntion.
I am trying run the below code however its giving me "TypeError: FabricUserControllers is not a constructor" error which is not handle in try catch{} block
Please see below code
let FabricUserControllers3 = require("./FabricUserController");
GetAllProduce: function (req, res, next) {
try{
let output = {};
var resArray = new Array();
let VZID = req.body.username;
console.log('test', 'GetAllProduce')
console.log('USername', VZID)
MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
if (err) {
let connError = new Error(500, "Error connecting to TEST database", err);
res.status(connError.status).json(connError);
} else {
let query = {};
client.db(config.Database.TEST.dbName).collection("Produce").find(query).toArray(function (err, response) {
console.log(response);
if (err) {
let roleError = new Error(500, "Error getting Produce information", err);
res.status(500).json(roleError);
} else if (response.length > 0) {
//DO someting here
//FabricUserControllers3 = {};
FabricUserControllers3 = new FabricUserControllers();// getting issue here
FabricUserControllers3.GetAll((VZID), (response) => {
console.log("data result", result)
res.status(200).json(response);
client.close();
})
} else {
output.message = "Produce doesn't exist";
res.status(409).json(output);
client.close();
}
});
}
});
}catch(e){
if (e instanceof TypeError){
console.log('error1', e.message);
printError(e,true);
}else{
console.log("error2", e.message);
printError(e, false);
}
}
},
FabricUserController.js
'use strict';
const {
FileSystemWallet,
Gateway
} = require('fabric-network');
const fs = require('fs');
const path = require('path');
var MongoClient = require('mongodb').MongoClient;
var Client = require('node-rest-client').Client;
var client = new Client();
const configPath = path.resolve(__dirname, '..', 'config', 'Config.json');
const configJSON = fs.readFileSync(configPath, 'utf8');
const config1 = JSON.parse(configJSON);
var connection_file = config1.connection_file;
var appAdmin = config1.appAdmin;
var gatewayDiscovery = config1.gatewayDiscovery;
var appAdminSecret = config1.appAdminSecret;
var orgMSPID = config1.orgMSPID;
var caName = config1.caName;
const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
let response = {};
class FabricUserControllers {
constructor() {
console.log("constructer called")
}
async ProduceRegistration(Username, produceid, callback) {
// Create a new file system based wallet for managing identities.
try {
const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
setTimeout(() => {
cb();
resolve();
}, timeout);
});
let query2 = {}
query2.PRODUCEID = produceid;
// console.log('PRODUCEID',produceid)
var PRODUCE = {};
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
console.log('Username', Username)
// Check to see if we've already enrolled the user.
const userExists = await wallet.exists(Username);
if (!userExists) {
console.log('An identity for the user: ' + Username + ' does not exist in the wallet');
console.log('call the registerUser before retrying');
response.data = null;
response.httpstatus = 400;
response.message = `An identity for the ${Username} does not exist in the wallet`;
return response;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccpPath, {
wallet,
identity: Username,
discovery: {
enabled: false,
asLocalhost: true
}
});
///
MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
if (err) {
// let connError = new Error(500, "Error connecting to TEST database", err);
response.data=null;
response.httpstatus = 500;
response.message = "Error connecting to TEST database :" + err;
// res.status(connError.status).json(connError);
return response;
} else {
client.db(config.Database.TEST.dbName).collection("Produce").find(query2).toArray(function (err, docs) {
if (err) {
response.httpstatus = 500;
response.message = "Error with DB :" + err;
return response;
}
else{
console.log("blockchain_status", docs[0].blockchain_status)
console.log('Role name DB',docs);
console.log('Role name DB1',docs[0]);
if(docs[0].STATUS)
PRODUCE.produceid = docs[0].PRODUCEID;
PRODUCE.produceName = docs[0].PRODUCE;
PRODUCE.farmLocation = docs[0].FARMLOCATION;
PRODUCE.plantingDate = docs[0].PLANTINGDATE;
PRODUCE.harvestDate = docs[0].HARVESTDATE;
PRODUCE.status = docs[0].STATUS;
PRODUCE.produceQuantites = docs[0].VARIETY;
PRODUCE.gapInfo = docs[0].GAP;
PRODUCE.farmerID = docs[0].farmerID;
console.log('Produce', PRODUCE);
const doStuffAsync = async () => {
setAsyncTimeout(async () => {
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('dfarmchannel');
// Get the contract from the network.
const contract = network.getContract(config1.chaincodeName);
var args = JSON.stringify(PRODUCE)
console.log("type of arg", typeof (args));
// Submit the specified transaction.
// console.log('produceID', args.produceID);
if(args==null || args==''){
console.log('Server not responding please try again');
}else
{
const result = await contract.submitTransaction('ProduceRegistration', args);
var argsJson = JSON.parse(result)
// console.log('result', argsJson)
// console.log('result1', result)
if(argsJson.produceID !="" && argsJson.produceID !=null && argsJson.produceID !="undefined" && argsJson.produceID !=undefined){
// // return false;
response.data = result
response.httpstatus = 200;
response.message = `Transaction has been submitted ansd successfull with Result :${result}`;
return callback(response);
// console.log('result before', response);
// console.log('Transaction has been submitted ansd successfull with Result :' + result);
}else{
console.log('blockchain server not responed')
// return false
response.httpstatus = 500;
response.message = `Please enter produce ID :`;
return response;
}
}
}, 4000);
};
doStuffAsync();
}
client.close();
})
}
})
await gateway.disconnect();
}
catch (error) {
// if(error) throw error;
response.error = error;
response.httpstatus = 500;
response.message = "Failed to enroll admin due to above error";
return response;
}
};
}
module.exports = FabricUserControllers;
#Abhirock, on your main file you have:
let FabricUserControllers3 = require("./FabricUserController");
FabricUserControllers3 = new FabricUserControllers();// getting issue here
You are trying to override FabricUserControllers3 creating a new object FabricUserControllers but you are not importing it. Try next solution to see if it solves your problem:
const FabricUserController = require("./FabricUserController");
const fabricUserControllers3 = new FabricUserController();
Hope it helps :))
Use kOA2 + node js + ajax to grab the web page data and display the result information on the front page:
query.js
const superagent = require('superagent');
const charset = require('superagent-charset');
const cheerio = require('cheerio');
charset(superagent);
function Rate(from, to, queryNumber) {
this.from = from;
this.to = to;
this.queryNumber = queryNumber;
}
module.exports = Rate;
Rate.query = function query(rate, callback) {
let URL = 'http://qq.ip138.com/hl.asp?from=' + rate.from + '&to=' + rate.to + '&q=' + rate.queryNumber;
superagent.get(URL)
.charset('gbk')
.end((err, sres)=> {
if (err) {
return next(err);
}
var $ = cheerio.load(sres.text);
var queryResult = [];
queryResult[0] = $(".rate td").eq(4).text();
queryResult[1] = $(".rate td").eq(5).text();
callback(null, queryResult);
})
};
index.js
const index = require('koa-router')();
const Rate = require('../models/query');
index.get('/s*', async (ctx, next) => {
let rate = new Rate(ctx.query.from, ctx.query.to, ctx.query.queryNumber);
await Rate.query(rate, (err, queryResult) => {
if (err) {
return next(err);
} else {
return ctx.render('query', {
title: '查询结果',
rate: queryResult[0],
amount: queryResult[1]
});
return next();
}
});
when visit “/s*” page, appear:(Node: 808) UnhandledPromiseRejectionWarning: Unhandled hate rejection (rejection id: 1): Error: Can not set headers after they are sent. Error, and the page can not jump.
Tried a lot of ways, but still do not know where to return in advance.
Is now known, because after the end of ctx, but also to call render to write data. The The But that is not where to change. Pls Help me.
Please update
const index = require('koa-router')();
const Rate = require('../models/query');
index.get('/s*', async (ctx, next) => {
let rate = new Rate(ctx.query.from, ctx.query.to, ctx.query.queryNumber);
await Rate.query(rate, (err, queryResult) => {
if (err) {
return next(err);
} else {
return ctx.render('query', {
title: '查询结果',
rate: queryResult[0],
amount: queryResult[1]
});
return next();
}
});
to
const index = require('koa-router')();
const Rate = require('../models/query');
index.get('/s*', async (ctx, next) => {
let rate = new Rate(ctx.query.from, ctx.query.to, ctx.query.queryNumber);
await Rate.query(rate, (err, queryResult) => {
if (err) {
return next(err);
} else {
return ctx.render('query', {
title: '查询结果',
rate: queryResult[0],
amount: queryResult[1]
});
}
});
im working in an existing project, and i have a problem driving me insane:
the routes are getting called twice or maybe even more, this happens when any route called take too long to respond
i think the problem is in this file, a dynamic routing attempt
var express = require('express');
var recaptcha = require('express-recaptcha');
//Site key, Secret key
recaptcha.init('xxxxx', 'yyyyy');
/**
* Routes middleware
* Check all requests
*/
module.exports = function(app, passport, memoryCache) {
var router = express.Router();
var config = require('app/config/settings.js');
router.use(function(req, res, next) {
console.log("touch");
console.log(req.url);
/**
* Make visible req / res on template layout
*/
res.locals.req = req;
res.locals.res = res;
/**
* Url filter
*/
var aryUrl = req.path.split('/').filter(Boolean);
try {
var root = '';
var controller = '';
var controllerPrototype = '';
var module = '';
var method = '';
var url = '';
var itemId = '';
var privacity = '';
var session = '';
switch (req.originalMethod) {
case 'GET':
method = 'get';
break;
case 'POST':
method = 'post';
break;
case 'PUT':
method = 'put';
break;
case 'DELETE':
method = 'delete';
break;
}
if (aryUrl.length == 0) {
root = '/';
} else {
root = aryUrl[0];
}
switch (root) {
case '/':
privacity = 'private';
session = 'General';
module = 'app/controllers/indexController';
controller = 'index';
controllerPrototype = 'root';
url = '/';
break;
case 'index':
privacity = 'private';
session = 'General';
module = 'app/controllers/indexController';
controller = 'index';
controllerPrototype = aryUrl[1];
url = '/index/' + aryUrl[1];
break;
case 'evaluaciones':
privacity = 'private';
session = 'PortalEval';
module = 'app/controllers/view-private/portalEvaluacionController';
controller = 'portalEvaluacion';
controllerPrototype = 'view';
url = '/evaluaciones';
if (aryUrl.length == 2) {
if (aryUrl[1] === 'antesdelcurso' || aryUrl[1] === 'despuesdelcurso') {
url = url + '/' + aryUrl[1];
} else {
controller = '';
}
}
break;
case 'relatores':
privacity = 'private';
session = 'RelatorEval';
module = 'app/controllers/portalRelatoresIndexController';
controller = 'portalRelatores';
controllerPrototype = 'view';
url = '/relatores';
break;
case 'api-pc':
privacity = 'public';
session = (req.user)? req.user.tipoSession : '';
var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
return chr.toUpperCase();
});
ctrl = 'api' + ctrl.charAt(0).toUpperCase() + ctrl.slice(1);
module = 'app/controllers/api-public/' + ctrl + 'Controller';
controller = ctrl;
if (aryUrl.length == 4) {
itemId = '/:id';
}
controllerPrototype = aryUrl[2];
url = '/api-pc/' + aryUrl[1] + '/' + aryUrl[2] + itemId;
break;
case 'api-pt':
privacity = 'private';
session = (req.user)? req.user.tipoSession : '';
var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
return chr.toUpperCase();
});
ctrl = 'api' + ctrl.charAt(0).toUpperCase() + ctrl.slice(1);
module = 'app/controllers/api-private/' + ctrl + 'Controller';
controller = ctrl;
if (aryUrl.length == 4) {
itemId = '/:id';
}
controllerPrototype = aryUrl[2];
url = '/api-pt/' + aryUrl[1] + '/' + aryUrl[2] + itemId;
break;
case 'view-pc':
privacity = 'public';
session = (req.user)? req.user.tipoSession : '';
var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
return chr.toUpperCase();
});
module = 'app/controllers/view-public/' + ctrl + 'Controller';
controller = ctrl;
if (aryUrl.length == 4) {
itemId = '/:id';
}
controllerPrototype = aryUrl[2];
url = '/view-pc/' + aryUrl[1] + '/' + aryUrl[2] + itemId;
break;
case 'view-pt':
privacity = 'private';
session = (req.user)? req.user.tipoSession : '';
var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
return chr.toUpperCase();
});
module = 'app/controllers/view-private/' + ctrl + 'Controller';
controller = ctrl;
if (aryUrl.length == 4) {
itemId = '/:id';
}
controllerPrototype = aryUrl[2];
url = '/view-pt/' + aryUrl[1] + '/' + aryUrl[2] + itemId;
break;
case 'auth':
/**
* Local Login
*/
var successGetLog = function(req, res) {
res.render('login/get.html', {
layout: 'layout/auth.html',
entorno: config.config_entorno.empresa,
message: req.flash('loginMessage'),
loginAttempts: req.flash('loginAttempts')
});
};
var successPostLog = function (req, res) {
var loginAttempts = res.locals.req.user.loginAttempts;
if (loginAttempts >= 4){
recaptcha.verify(req, function(error){
if(error){ //Falla de verificacion de captcha
res.render('login/get.html', {
layout: 'layout/auth.html',
entorno: config.config_entorno.empresa,
message: req.flash('loginMessage'),
loginAttempts: loginAttempts,
captcha:recaptcha.render()
});
} else { //Exito de verificacion de captcha
res.redirect('/');
}
});
} else {
res.redirect('/');
}
};
var successGetLogout = function(req, res) {
req.logout();
res.redirect('/');
};
router.route('/auth/login').get(successGetLog);
router.route('/auth/login').post(passport.authenticate("local-login", {failureRedirect: '/auth/logout'}), successPostLog);
router.route('/auth/logout').get(successGetLogout);
/**
* Encuesta Local Login
*/
var successGetPortalLog = function(req, res) {
if (req.query.rut != undefined || req.query.token == 'bciboost') {
if (req.query.rut != undefined && req.query.token == 'bciboost') {
console.log('casi');
req.body = {
rut: req.query.rut,
password: 'null'
};
passport.authenticate('portaleval-link-login', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
res.render('portalevaluacionapp/portal_evaluacion_login.html', {
layout: 'layout/empty.html',
entorno: config.config_entorno.empresa,
message: req.flash('loginMessage'),
access: req.path,
});
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
if (user) {
res.redirect('/evaluaciones');
}
});
})(req, res, next);
} else {
res.render('portalevaluacionapp/portal_evaluacion_login.html', {
layout: 'layout/empty.html',
entorno: config.config_entorno.empresa,
message: 'Existe un problema al iniciar sesión',
access: req.path,
});
}
} else {
if (Object.keys(req.session.passport).length !== 0 && req.session.passport.constructor === Object && req.path === '/auth/evaluaciones' && req.session.passport.user.type === 'PortalEval') {
res.redirect('/evaluaciones');
} else {
res.render('portalevaluacionapp/portal_evaluacion_login.html', {
layout: 'layout/empty.html',
entorno: config.config_entorno.empresa,
message: req.flash('loginMessage'),
access: req.path,
});
};
}
}
var successPostPortalLog = function(req, res) {
res.redirect(req.path.replace('/auth', ''));
};
var successGetPortalLogout = function(req, res) {
req.logout();
res.redirect(req.path.replace('/logout', ''));
};
var successGetPortalRelatorLogout = function(req, res) {
req.logout();
res.redirect("/auth/relatores");
};
if (req.path === '/auth/evaluaciones' || req.path === '/auth/evaluaciones/antesdelcurso' || req.path === '/auth/evaluaciones/despuesdelcurso') {
var rutAux = req.body.rut;
req.body = {
rut: (typeof rutAux === 'undefined' || rutAux === '')? 'null': req.body.rut,
password: 'null'
};
}
router.route('/auth/evaluaciones').get(successGetPortalLog);
router.route('/auth/evaluaciones/antesdelcurso').get(successGetPortalLog);
router.route('/auth/evaluaciones/despuesdelcurso').get(successGetPortalLog);
router.route('/auth/evaluaciones').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog);
router.route('/auth/evaluaciones/antesdelcurso').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog);
router.route('/auth/evaluaciones/despuesdelcurso').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog);
router.route('/auth/evaluaciones/logout').get(successGetPortalLogout);
router.route('/auth/evaluaciones/logout/antesdelcurso').get(successGetPortalLogout);
router.route('/auth/evaluaciones/logout/despuesdelcurso').get(successGetPortalLogout);
var successGetRelatorLog = function(req, res) {
res.render('portalrelatoresapp/portal_relatores_login.html', {
layout: 'layout/empty.html',
entorno: config.config_entorno.empresa,
message: req.flash('loginMessage'),
access: req.path,
});
};
var successPostRelatorPortalLog = function(req, res) {
res.redirect(req.path.replace('/auth', ''));
};
router.route('/auth/relatores').get(successGetRelatorLog);
router.route('/auth/relatores').post(passport.authenticate("portalrelatores-login", {failureRedirect: '/auth/relatores'}), successPostPortalLog);
router.route('/auth/relatores/logout').get(successGetPortalRelatorLogout);
break;
default:
break;
}
if (controller != '') {
var controllerDynamic = require(module);
controllerDynamic.req = req;
controllerDynamic.res = res;
/**
* Auth validation
*/
if (privacity == 'private') {
if (req.isAuthenticated()) {
if (session == 'General') {
if (controllerDynamic.auth.indexOf('PortalEval') != -1) {
var err = new Error(402);
throw err;
}
} else
if (session == 'PortalEval') {
if (controllerDynamic.auth.indexOf('General') != -1) {
var err = new Error(401);
throw err;
}
} else
if (session == 'RelatorEval') {
if (controllerDynamic.auth.indexOf('General') != -1) {
var err = new Error(401);
throw err;
}
}
//==============================================================================
else
if (session == 'PortalRelator') {
if (controllerDynamic.auth.indexOf('PortalRelator') == -1) {
var err = new Error(402);
throw err;
}
}
//==============================================================================
else {
var err = new Error(404);
throw err;
}
} else {
if (controllerDynamic.auth.indexOf('PortalEval') != -1) {
var err = new Error(402);
throw err;
} else
if (controllerDynamic.auth.indexOf('General') != -1) {
var err = new Error(401);
throw err;
} else {
var err = new Error(404);
throw err;
}
}
}
/**
* Check the "auth" atribute of a controller
*/
// if (controllerDynamic.auth.indexOf(controllerPrototype) != -1) {
// }
/**
* Final validation
*/
var isValid = true;
if (aryUrl.length > 4) {
isValid = false;
}
if (method == '') {
isValid = false;
}
if (typeof controllerDynamic[controllerPrototype] !== "function") {
isValid = false;
}
if (isValid) {
router.route(url)[method](function(ctrlReq, ctrlRes){
controllerDynamic[controllerPrototype](ctrlReq, ctrlRes);
});
} else {
res.status(404).send('Not found');
}
}
next();
} catch (e) {
if (e.message == 401) {
res.status(401).redirect('/auth/login');
} else
if (e.message == 402) {
res.status(401).redirect('/auth' + url);
} else {
res.status(404).send('Not found 2');
}
}
});
app.use('/', router);
};
in fact that console.log(touch) get called twice if the route doesn't respond fast (in less than 8 minutes) i had no idea what is going on
Thanks guys!
I am playing with NodeJS and for this purpose created an email extractor. Somehow when i create multiple http requests the node.exe memory useage in windows task manager keeps increasing. I understand that the node needs more memory to process the requests but what i noticed that this memory usage does not come down even after all requests have been successfully processed.
When i start nodejs it consumes about 35000K memory but after about 80-100 request this goes upto 50000K and stays.
Here is my simple email extractor module:
var request = require('request'),
cheerio = require('cheerio'),
async = require('async'),
urlHelper = require('url');
function Extractor(config) {
this.baseUrl = config.url;
this.parsedUrl = urlHelper.parse(config.url);
this.urls = [];
this.emails = [];
}
Extractor.prototype.getEmails = function getEmails(html) {
var foundEmails = html.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi) || [];
if(foundEmails.length) this.emails = this.emails.concat(foundEmails);
}
Extractor.prototype.extract = function extract(html) {
var $ = cheerio.load(html),
that = this;
if($('body')){
this.getEmails($('body').html());
}
if(!this.emails.length){
$("a[href^='http://" + this.parsedUrl.host + "'], a[href^='https://" + this.parsedUrl.host + "'], a[href^='/'], a[href^='./'], a[href^='../']").each(function(k, v) {
that.urls.push(urlHelper.resolve(that.baseUrl, $(v).attr('href')));
});
}
};
/**
* Process the base URL
*/
Extractor.prototype.processBase = function processBase(next) {
request(this.baseUrl, function(err, response, body) {
return next(err, body);
});
}
/**
* Process the internal pages
*/
Extractor.prototype.processInternal = function processInternal(cb) {
var that = this;
async.whilst(
// while this condition returns true
function () { return that.emails.length === 0 && that.urls.length > 0; },
// do this
function (callback) {
request(that.urls.shift(), function (err, response, body) {
var $ = cheerio.load(body);
if($(body)){
that.getEmails($('body').html());
}
callback(); // async internal, needs to be called after we are done with our thing
});
},
// call this if any errors occur. An error also stops the series
// this is also called on successful completion of the series
function (err) {
cb(that);
}
);
}
Extractor.prototype.process = function process(next) {
var that = this;
this.processBase(function(err, html) {
if(err) {
console.log(err);
} else {
that.extract(html);
if(!that.emails.length) {
that.processInternal(function(res) {
return next(null, that);
});
}
}
});
}
module.exports = Extractor;
and here is how i call it:
var express = require('express');
var router = express.Router();
var Extractor = require('../services/Extractor');
router.get('/', function(req, res) {
res.json({msg: 'okay'});
var extractor = new Extractor({url: 'http://lior-197784.use1-2.nitrousbox.com:4000/crawl'});
extractor.process(function(err, res) {});
});
module.exports = router;
in this code: if i try to pass this.handler as parameter to server.createServer() , then i get no response (the page keeps loading in browser). but if i use server.createServer(function(req, res) { //same code here as in handler() }) , then it works. what am i doing wrong?
var Con = module.exports = function() {
process.EventEmitter.call(this);
}
var createServer = module.exports.createServer = function(options) {
console.log('start');
this.port = options.port || 9122;
this.secure = options.secure || false;
if(this.secure === true)
if(!options.key || !options.certificate)
this.secure = false;
else {
this.key = options.key;
this.certificate = options.certificate;
}
if(this.secure) {
this.server = require('https');
var fs = require('fs');
var opt = {
key: fs.readFileSync('privatekey.pem'),
cert: fs.readFileSync('certificate.pem')
};
this.server.createServer(opt, this.handler).listen(this.port);
} else {
this.server = require('http');
this.server.createServer(this.handler).listen(this.port);
}
}
Con.prototype.handler = function(req, res) {
console.log('request');
res.writeHead(200);
res.write(req.url);
res.end();
}
var Con = function() {
process.EventEmitter.call(this);
}
That's your constuctor
module.exports = new Con();
That's your instance
var createServer = module.exports.createServer = function(options) {
console.log('start');
this.port = options.port || 9122;
this.secure = options.secure || false;
if(this.secure === true)
if(!options.key || !options.certificate)
this.secure = false;
else {
this.key = options.key;
this.certificate = options.certificate;
}
if(this.secure) {
this.server = require('https');
var fs = require('fs');
var opt = {
key: fs.readFileSync('privatekey.pem'),
cert: fs.readFileSync('certificate.pem')
};
this.server.createServer(opt, this.handler).listen(this.port);
} else {
this.server = require('http');
this.server.createServer(this.handler).listen(this.port);
}
}
.createServer is now a method on the instance rather then the constructor.
Since it's on the instance it also has access to the .handler method defined on the instance through the prototype.