Exporting a function inside a function - node.js

app.js
var a = function(){
var b = function(){
console.log("hello")
}
}
module.exports = {a}
index.js
console.log(require("./app.js").a().b())
I wantr to get the output "hello" but i am getting error can call property b of undefined
Please help to obtain the result

try this
var a = function () {
var b = function () {
console.log("hello")
}
return {b:b};
}

Related

Export functions Nodejs

I'm using module.exports to export list of module. Below is my
Models/Message.js
var msgModel = function()
{
var getMsg = function() {
return "Hello World";
}
return{
getMsg : getMsg
}
}
module.exports = msgModel;
Below is my app.js
var msgModel = require('./Models/Message');
console.log(msgModel.getMsg());
It raised me error
console.log(msgModel.getMsg());
^
I can't figure out the problem.
You need to do console.log(msgModel().getMsg());. This is because msgModel is a function. I would suggest rewriting your msgModel like the example below instead to achieve the call you wanted.
var msgModel = {
getMsg: function() {
return "Hello World";
}
};
module.exports = msgModel;
You could do something like this:
var msg = new msgModel();
console.log(msg.getMsg());
You should export a function and invoke it in the main app.js
for example:
app.js
var msgModel = require('./Models/Message');
msgModel();
Message.js
var getMsg = function(){
console.log("Hello World!");
};
module.exports = getMsg;
You could write it this way in order to group more functions:
module.exports = {
getMsg: function() {
return "Hello World";
},
anotherFnc: function () {
...
}
};
then you could use:
var msgModel = require('./Models/Message');
console.log(msgModel.getMsg());

how to call methods with variable in node.js

how to call methods with variable in node.js
this is so that ;
var file=require("./file");
var method=b;
file.method();
//output
//error : TypeError: file.method is not a function
how to use it?
ok try this then
//file.js
module.exports = {
index: function () {
console.log("index called");
},
index2 :function() {
console.log("index2 called");
} ,
index3 : function () {
console.log("index3 called");
}
};
then
app.get("file/:method",function (req,res)
{
var method = req.params.name;
var file = require('./file');
file[method]();
}
app.get("file/:method",function (req,res)
{
var file("./file");
var method=req.params.name;
file.method();
this is what ı want to tell

Node.js : Call function using value from callback or async

I have written below .js file to call below defined function.
objectRepositoryLoader.readObjectRepository() returns me a hashmap from where i have to use values in enterUserName(), enterPassword(), clickLoginButton() functions.
var path = require('path');
var elementRepoMap = {}
var LandingPage = function(){
var fileName = path.basename(module.filename, path.extname(module.filename))
objectRepositoryLoader.readObjectRepository(fileName+'.xml' , function(elementRepo){
console.log(elementRepo) //values are being printed here
this.elementRepoMap = elementRepo
});
this.enterUserName = function(value){
console.log(elementRepoMap) //values are not being printed here
//Some Code
};
this.enterPassword = function(value){
//Some Code
};
this.clickLoginButton = function(){
//Some Code
};
};
module.exports = new LandingPage();
The objectRepositoryLoader.readObjectRepository() function defined in another file is as below:
var ObjectRepositoryLoader = function() {
this.readObjectRepository = function(fileName, callback) {
var filePath = './elementRepository/'+fileName;
this.loadedMap = this.objectRepoLoader(filePath, function(loadedMap){
return callback(loadedMap);
});
}
this.objectRepoLoader = function(filePath, callback){
if (filePath.includes(".xml")) {
this.xmlObjectRepositoryLoader(filePath, function(loadedMap){
return callback(loadedMap);
});
}
this.xmlObjectRepositoryLoader = function (xmlPath, callback){
var innerMap = {};
var elementName;
fs.readFile(xmlPath, "utf-8",function(err, data) {
if(err){
console.log('File not found!!')
}
else{
var doc = domparser.parseFromString(data,"text/xml");
var elements = doc.getElementsByTagName("A1");
for(var i =0 ; i< elements.length;i++){
var elm = elements[i];
elementName = elm.getAttribute("name");
var params = elm.getElementsByTagName("AS");
innerMap = {};
for(var j =0 ; j< params.length;j++){
var param = params[j];
var locatorType = param.getAttribute("type");
var locatorValue = param.getAttribute("value");
innerMap[locatorType] = locatorValue;
}
loadedMap[elementName] = innerMap;
innerMap={};
};
}
return callback(loadedMap);
});
};
How can I call enterUserName(), enterPassword(), clickLoginButton() function from spec.js file and is there any way I can avoid using callback and use async.js and call enterUserName(), enterPassword(), clickLoginButton() from spec.js file ?
EDIT
I have modified my file like below:
this.xmlObjectRepositoryLoader = function (xmlPath){
var innerMap = {};
var elementName;
var filePath = xmlPath+'.xml'
var self = this
return new Promise(
function(resolve, reject){
console.log("In xmlObjectRepositoryLoader : "+filePath)
self.readFilePromisified(filePath)
.then(text => {
var doc = domparser.parseFromString(text,"text/xml");
var elements = doc.getElementsByTagName("Element");
for(var i =0 ; i< elements.length;i++){
var elm = elements[i];
elementName = elm.getAttribute("name");
var params = elm.getElementsByTagName("param");
innerMap = {};
for(var j =0 ; j< params.length;j++){
var param = params[j];
var locatorType = param.getAttribute("type");
var locatorValue = param.getAttribute("value");
innerMap[locatorType] = locatorValue;
}
map[elementName] = innerMap;
innerMap={};
}
console.log(map) // prints the map
resolve(text)
})
.catch(error => {
reject(error)
});
});
}
this.readFilePromisified = function(filename) {
console.log("In readFilePromisified : "+filename)
return new Promise(
function (resolve, reject) {
fs.readFile(filename, { encoding: 'utf8' },
(error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
})
})
}
I am calling above function from another file as below:
objectRepositoryLoader.readObjectRepository(fileName)
.then(text => {
console.log(text);
})
.catch(error => {
console.log(error);
});
But it gives me error as
.then(text => { ^
TypeError: Cannot read property 'then' of undefined
In this case how can I use promise to call another promise function and then use the returned value in one more promise function and return calculated value to calling function where I can use the value in other functions. I sound a bit confused. Please help
You can use async.waterfall and async.parallel to perform this task
see the reference
I just tried your code to make it working, I explained the way of implementation in comment.
async.waterfall([
function(next){
objectRepositoryLoader.readObjectRepository(fileName+'.xml' ,next)//pass this next as parameter in this function defination and after manipulation return result with callback like this(null,result)
}
],function(err,result){
if(!err){
//Do wahtever you want with result
async.parallel([
function(callback){
this.enterUserName = function(value){
console.log(elementRepoMap)
//Some Code
};
},
function(callback){
this.enterPassword = function(value){
//Some Code
};
},
function(callback){
this.clickLoginButton = function(){
//Some Code
};
}
], function(err, results) {
// optional callback
};
}
})

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(); }
);

how to return value from this scope (Node.js)

I have a Node.js module which return memory used:
//meminfo.js
module.exports = myObj;
myObj = (function() {
var pub = {};
pub.getmem = function() {
meminfo.list(function(memused) {
return memused;
});
};
return pub;
})();
If I want to retrieve memused by this:
//main.js
var meminfo = require('./meminfo');
console.log(myObj.getmem());
Then could you give me some suggestions about how to return 'memused' from this in meminfo.js:
meminfo.list(function(memused) {
return memused;
});

Resources