making event in module.exports functions - node.js

I'm trying to make a module with an even that I could call from the index file (after a require).
My code includes var events = require("events"); and I've wrote only the tricky part here.
index.js:
var reqw = require('./module.js');
reqw.on('data', function(d) {
console.log(d);
});
module.js:
module.exports = {
listaccts: function() {
events.EventEmitter.call(this);
}
}
util.inherits(exports.listaccts, events.EventEmitter);
exports.listaccts.prototype.listme = function() {
thisList = this;
var req = https.request(requestOptions, function(res) {
res.on('data', function(chuck) {
store = chuck;
});
res.on('end', function(d) {
thisList.emit("data", store.toString());
});
});
}
Searched the whole we and yet to find a proper answer..

Modified your code slightly :
module.js
function listaccts(){
}
util.inherits(listaccts, EventEmitter);
listaccts.prototype.listMe = function(){
var self = this;
var store = [];
console.log('here');
var req = https.request(requestOptions, function(res) {
res.on('data', function(chuck) {
console.log('data');
store.push(chuck);
});
res.on('end', function() {
console.log('end');
self.emit("data", store);
});
});
req.end();
};
module.exports = listaccts;
index.js
var reqw = require('./module');
var obj = new reqw();
obj.listMe();
obj.on('data', function(err, data) {
console.log(err);
});
req.end is important, I have forgot to include and got a never-ending cycle.
Created instance for binding this, so no need for EventEmitter.call.
Maybe you want to the listMe function to inside your constructor.
Hope this help.

Related

multiple http get calls nodejs

Thanks for looking into the code.
Here I am fetching some data using feed parser and taking out id's in navcodes array variable and wants to use these Id to make http call.Please find code below.
function processNavCode(){
var mfId = [53];
var preTitle = '';
var navCodes = [];
mfId.forEach(function(id){
var query = "http://portal.xyz.com/Rss.aspx?mf="+id;
feed(query, function(err, feeds) {
if (err) {
throw err;
}
feeds.forEach(function(feed){
var link = feed.link;
var title = feed.title;
var navCode = link.substr(link.length - 6);
if(title.split('-')[0].trim() != preTitle){
preTitle = title;
counter ++;
}
if(parseInt(navCode) != '')
navCodes.push = parseInt(navCode);
});
});
async.eachSeries(navCodes,insertbulkMFValues,function(){
console.log('I am done');
});
// insertbulkMFValues(navCode);
//Directly call insertbulkMFValues function
});
}
I have also tried to call the insertbulkMFValues directly as commented now but due to async nature of nodejs, I am getting the error of either 'Socket hang up' or 'read ECONNRESET'. I checked and used async but not able to work with that also.
var insertbulkMFValues =function(navCode,callback){
var options = {
host: 'www.quandl.com',
path: '/api/v3/datasets/AMFI/'+navCode+'.json?api_key=123456789&start_date=2013-08-30',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
var req1 = https.request(options, function(response) {
var body = '';
response.setEncoding('utf8');
response.on('data', function(chunk) {
body += chunk;
});
response.on('end', function() {
if(typeof body === "string") {
var json = JSON.parse(body);
}
var mfData = json.dataset.data;
var schemeId = json.dataset.dataset_code;
var schemeName = json.dataset.name;
var isinCode = json.dataset.description;
var valueData=[];
for (var k = 0; k < mfData.length; k++) {
var myDate = new Date(mfData[k][0]);
valueData.push({
date:myDate,
NAV:parseFloat(mfData[k][1]).toFixed(2)
});
}
var query = { "navCode": schemeId };
var newData = {
createdDate: Date.now(),
navCode: schemeId,
schemeCode:count,
schemeName:schemeName,
ISINCode:isinCode,
values:valueData
};
MHistory.findOneAndUpdate(query, newData , {upsert:true}, function(err, doc){
if(err)
console.log('Errorr');
else
console.log('Success');
});
});
});
req1.on('error', function(e) {
console.log('problem with request: ' + e.message);
callback(true);
});
req1.end();
}
Thanks in advance..
J
You can directly call insertbulkMFValues for each navCode like:
if(parseInt(navCode) != '') {
insertbulkMFValues(navCode, function () {
console.log('something'}
});
}
Anything that you intend to do must be within the callback of the asynchronous function.
One option for you is to use the waterfall or parallel method of the async library to retrieve all feeds for each id and then invoke
async.eachSeries(navCodesAccumulated,insertbulkMFValues,function(){
console.log('I am done');
});
within the final result callback using the codes obtained.

unit testting using sinon+mockery+chai in node.js

I am very new to unit testing, so please guide me through the following: I am trying to unit test the following function...
helpers.js
function helpers() {
}
helpers.prototype.Amount = function(callback){
var Amount = 0;
app.models.xxx.find({}, function(err, res) {
if(err){
} else {
for(var i=0; i < res.length; i++){
Amount = Amount + res[i].hhhh;
}
return callback(null,Amount);
}
});
}
module.exports.helpers = helpers;
helpers-test.js
describe('helper', function(){
var AmountStub = sinon.stub(Helper.protoype,"getAmount");
it('should return the amount', function(done){
var helper = new Helper();
helper.getAmount(function(err, res){
assert.ifError(err);
});
done();
});
});
But i am receiving the following error:
/node_modules/sinon/lib/sinon/util/core.js:67
throw new TypeError("Should wrap property of object");
^
TypeError: Should wrap property of object
Please guide me through this. Also the way i am doing is right? Thanks in advance..
EDIT:
var Helper = require("../../server/helpers").helpers;
var helper = sinon.stub(
new Helper(),
"getAmount",
function (callback) { callback(1000); }
);
helper.getAmount(
function (value) {
expect(value).to.be.equal(1000);
done();
});
});
According to the sinon docs you need to pass an object itself, not its prototype.
var helper = sinon.stub(new Helper(), "getAmount");
In your case you would like to do stubbing inside the it test and provide the replacement for the function:
var helper = sinon.stub(
new Helper(),
"getAmount",
function (callback) { callback(dummyValue); }
);
helper.getAmount(
function (value) { done(); }
);

handling session variables inside http.request in express

Hi. When i print the req.session.mySessValue in UI , the value is empty. I think the assigning of req.session.mySessValue = dt.myValue; (express-session) is not proper. could anyone help me on this. Thanks in advance.my express code is
router.get('/', function(req, res, next) {
if(!req.xx) {
return res.redirect('/firstView');
}
var options = {
.......
};
var call = http.request(options, function(resp) {
resp.on('data', function(dt) {
var jsondata = JSON.parse(dt);
req.session.mySessValue = dt.myValue;
});
});
call.end();
call.on('error', function(e) {
console.log("error" +e.message)
});
var v = {
title: 'sample',
req : req
}
res.render('myview', v);
});

Issue with EventEmitter inheritance

I'm having a small issue, playing around with module patterns. I'm trying to attach an eventemitter to my library, but it doesn't seem to work and I get :
cmd.on('message',function(msg){
^
TypeError: undefined is not a function
My lib looks like :
var util = require('util');
var EventEmitter = require("events").EventEmitter;
var TestLib = function() {
var self = this;
function sendRandom(cb){
self.emit('message','whatever');
cb(null,0);
}
return {
init: function(cb) {
console.log('init');
cb(null);
},
run: function(params,cb){
console.log('running ',params);
sendRandom(function(err,res){
if(err){
cb(new Error(err));
}else{
cb(null,res);
}
});
},
close: function(cb) {}
};
};
util.inherits(TestLib, EventEmitter);
module.exports = TestLib;
And I call it as such :
var cmd = require(__dirname+'/bin/testlib.js')();
cmd.on('message',function(msg){
log(msg);
});
cmd.init(function(err){
if(err){
log(err);
}else{
cmd.run(line,function(err,res){
if(err){
log(err);
}else{
log(res);
}
});
}
});
I'm sure I'm overlooking something simple, but what?
see whether the example below helps you.
testLib.js
var EventEmitter = require('events').EventEmitter;
var util = require('util');
function TestLib(ms) {
var self = this;
EventEmitter.call(this);
this.random = function() {
//emitting 'random' event randomly
var ms = Math.random() * 100000 % 3000;
console.log('emitting random event in ' + ms + ' milliseconds');
setTimeout(function() {
self.emit('random', ms);
self.random();
}, ms);
return self;
}
}
util.inherits(TestLib, EventEmitter);
module.exports = TestLib;
test.js
var TestLib = require('./testLib');
new TestLib()
.random()
.on('random', function(ms) {
console.log('random event emitted after ' + ms + ' milliseconds');
});
to run it, execute node test.js

Different results using Node.js' module.exports in Yeoman

I am receiving different results with module.exports and would appreciate someone helping me shore up the obvious hole in my knowledge.
From the following code, I receive the result listed below it.
var generators = require('yeoman-generator');
var MyBase = generators.Base.extend({
helper: function() {
console.log('this is a helper method');
}
});
module.exports = MyBase.extend({
method1: function() {
console.log('method 1 just ran');
}
});
Result:
method 1 just ran
But if I place module.exports on its own line, and assign MyBase to it, I get the following result. Here is the code:
var generators = require('yeoman-generator');
var MyBase = generators.Base.extend({
helper: function() {
console.log('this is a helper method');
}
});
MyBase.extend({
method1: function() {
console.log('method 1 just ran');
}
});
module.exports = MyBase
Result:
this is a helper method
What is causing the difference in outputs?
I haven't been able to completely reproduce your issue, but the problem is almost certainly the fact that calling .extend on a generator returns a new generator with both the current and extended properties.
var generators = require('yeoman-generator');
var MyBase = generators.Base.extend({
helper: function() {
console.log('this is a helper method');
}
});
// Capture the output of the .extend function
var MyBase2 = MyBase.extend({
method1: function() {
console.log('method 1 just ran');
}
});
module.exports = MyBase2
Alternatively, you could just define multiple properties in one go
var MyBase = generators.Base.extend({
helper: function() {
console.log('this is a helper method');
},
method1: function() {
console.log('method 1 just ran');
}
});

Resources