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
Related
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());
I couldnt write function worked automatically (constructor) when file required in node.js..
this is so...file.js
module.exports = {
index: function () {
//code here
}
};
app.js
var file=require("./file");
res.send(file.index());
what I want...
module.exports = {
main :__constructor()
{
this.name="blabla";
},
index: function () {
//code here
this.name // will be used this place name variable
}
};
Use .prototype() to do this. Hope it helps!
const App = function(name) {
this.name = name
}
App.prototype.main = function() {
return this.name
}
b = new App('myName')
console.log(b.main())
//You can do module.exports = App and invoke it in another file
okey..but
module.exports = {
app :function (name)
{
this.name="blabla";
},
app.prototype.index: function () {
}
};
this does not work!!!
/var/www/public/nodeapi/app/v1/blog/index.js:19
app.prototype.index: function () {
const App = function(name) {
this.name = name
}
App.prototype.main = function() {
return this.name
}
b = new App('myName')
console.log(b.main())
//You can do module.exports = App and invoke it in another file
Something like this?
// file.js
class MyClass {
constructor() {
this.name = 'blabla';
}
index() {
console.log('name', this.name);
}
}
module.exports = new MyClass();
class blog {
constructor()
{
this.name="fookey";
}
index(callback)
{
var data={};
data.test=this.name;
callback(data);
}
}
module.exports=new blog();
TypeError: Cannot read property 'name' of undefined
why does not work?
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
};
}
})
I have a funciton inside a node-module:
//app.js
var minify = require("./minify.js")(app, express);
//minify.js
module.exports = function (app, express) {
...
function fileList(dir) {
return fs.readdirSync(dir).reduce(function(list, file) {
var name = path.join(dir, file);
var isDir = fs.statSync(name).isDirectory();
var isJs = name.endsWith('.js');
return list.concat(isDir ? fileList(name) : isJs ? [name] : [] );
}, []);
}
...
};
I want to change it to a method to make my code more readable.
I tried the following, without success:
module.fileList = function(dir) {
return fs.readdirSync(dir).reduce(function(list, file) {
var name = path.join(dir, file);
var isDir = fs.statSync(name).isDirectory();
var isJs = name.endsWith('.js');
return list.concat(isDir ? fileList(name) : isJs ? [name] : [] );
}, []);
module.prototype.fileList = function(dir) {
return fs.readdirSync(dir).reduce(function(list, file) {
var name = path.join(dir, file);
var isDir = fs.statSync(name).isDirectory();
var isJs = name.endsWith('.js');
return list.concat(isDir ? fileList(name) : isJs ? [name] : [] );
}, []);
}
I expect to be able to call the method usint this.fileList or minify.filelist, depending on my scope.
You can return object from exported function:
//minify.js
function fileList(dir) {
// ...
}
module.exports = function(app, express) {
//...
return {
fileList: fileList
};
}
//app.js
var minify = require("./minify.js")(app, express);
minify.fileList();
I think this way is easier :
minify.js
module.exports = {
fileList: function(app, express) {
// your code here
},
Method2: function() {
// another code here
}
}
And you can use it like this:
app.js
var minify = require('minify');
minify.fileList(app, express);
minify.Method2();
I got an angularJS' controller used in node-webkit app, how to call db.js ' save_db from angular's controller? code as follow, thanks:
angular.module('clk.controllers', [])
.controller('homeCtrl', ["$scope",function ($scope) {
$scope.post_it = function(tm) {
}
}])
db.js
var db = mongo.db(db_connection)
var users = db.collection('users')
exports.save_db = function (rec, cb) {
users.insert(rec, {
safe: true
}, function (err, records) {
cb(null, '')
});
};
you would simply require your db.js file and call the Node library as per usual e.g.
var db = require('./db.js');
var app = angular.module('clk.controllers', []);
app.controller('homeCtrl', ["$scope", function ($scope) {
$scope.post_it = function(tm) {
db.save_db(tm, function () {
console.log('record added');
});
};
}]);