How to call an external function in node js route - javascript

I am a little confused on how this works...
I am writing a node/express app and there is a function I just wrote in its own file, I need to use it in my route and I just want to call that function.
In the other file (tranformTheData.js) there is:
module.exports = {
tranformTheData:function (data){
console.log('whatever')
}
In my node app.js file I have
var formatJSON = require('./js').tranformTheData;
Can I just now use
formatJSON(data)
and utilitze this function? Or do I have to do something else, I have seen a few examples of doing this however they do not make sense to me.

You should do this:
// transformData.js
module.exports = {
formatJSON: function(data) {
console.log('whatever')
},
otherFunction: function() {
}
}
// app.js
var tranformTheData = require('./path/to/tranformTheData.js');
var formatJSON = tranformTheData.formatJSON;
var otherFunction = tranformTheData.otherFunction;
formatJSON(data); // this will work
module.exports in this case is exporting an object literal, and the object has two functions. Requiring that file and assigning it to a variable will assign that variable to the object literal, which then has access to its methods.
When you call those methods, you can then pass in whatever params you want. In the case of formatJSON, it's accepting the data param.

Make sure to add the missing closing bracket in transformTheData.js:
module.exports = {
tranformTheData: function(data) {
console.log('whatever');
}
};
Now you should be able to require the file using its filename and call the function as you are trying to do:
var formatJSON = require('./transformTheData').tranformTheData;
formatJSON(data);

Related

Is there a way to call a non-cloud function inside same file where the Firebase cloud functions were created?

I still can't wrap my head around how these functions work generally. For the project, I created a function that will be called by whenever that function URL is called. Afterwards, the called function also uses a utility function. This function is used multiple times so I only find it sensible to create them in a separate function, although whenever I use the function after deployment, I get this error.
TypeError: this.isMM is not a function
at exports.addOrder.functions.https.onRequest (/user_code/index.js:130:11)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)
at /var/tmp/worker/worker.js:783:7
at /var/tmp/worker/worker.js:766:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
I only have a single file, index.js where I place all my functions, although I'm not sure why above function isMM() is not being read. Below is the relevant codeblock (I have replaced the content of the functions for simplicity's sake.
exports.addOrder = functions.https.onRequest((req, res) => {
var newValue = req.query.my_info;
var anotherValue = req.query.another_info;
var my_info = this.isMM(newValue);
if(my_info){
var another_info = this.isMM(anotherValue);
if(another_info){
doThis();
}
}
});
isMM = (toCheck) => {
if(toCheck === 'someString'){
return true;
}
return false;
}
I wish to make isMM readable inside addOrder since this will be a reoccurring thing that I need to do for this project.
Just do as follows and don't use this .
var my_info = isMM(newValue);
if(my_info){
var another_info = isMM(anotherValue);
if(another_info){
doThis();
}
}

NodeJS - My method doesn't execute

inside my file ./functions/login_registration_functions.js
I have the following code
var methods = {
check_if_not_null: function (item_to_be_checked, item_to_store_the_checked_item) {
if(item_to_be_checked != null){
item_to_store_the_checked_item = item_to_be_checked;
}
}
};
module.exports = methods;
and I am calling it inside my routes.js file
var log_reg_funcs = require('./functions/login_registration_functions.js');
and I am calling the method inside my put call
log_reg_funcs.check_if_not_null(req.body.title, request.title);
but it doesn't work. when I replace the above code with below:
if(req.body.title != null){
request.title = req.body.title;
}
it works fine
why am I missing here?
When you are doing this:
item_to_store_the_checked_item = item_to_be_checked;
when item_to_store_the_checked_item is the argument to your function, then you are not changing the original variable that was used when calling your function but only your local copy of the passed value that is in your function.
If you passed and object and changed one of its properties then it would work as you expect.
For example if you had:
var methods = {
check_if_not_null: function (item_to_be_checked, object_to_store, object_key) {
if(item_to_be_checked != null){
object_to_store[object_key] = item_to_be_checked;
}
}
};
then you'd be able to do:
log_reg_funcs.check_if_not_null(req.body.title, request, 'title');
(it's strange for JavaScript to use underscores instead of camelcase but I'm keeping your style here)

access callback response data from Ajax using Javascript Revealing Prototype Pattern

I am trying to structurise JS code using Revealing Prototype Pattern.
My basic usecase is: Create different types of entities like Person, Technology. Each entity has its own tags. In order to get these tags i make an ajax call which returns an object of tags. I want to access this object in my implementation. But i am not sure how to do it in right way.
My attempt is as follows:
var Entity= function (url) {
this.url = url; /*variable that can be shared by all instances*/
var entityTags;
};
Entity.prototype = function () {
var create = function (type, values) {
//code for creating
}
var update = function (type, values) {}
var tags = function () {
AjaxCall(' ', this.url, {data:data}, 'callbackAfterGetTags', '');
callbackAfterGetTags=function(responseFromAjax)
{
entityTags=responseFromAjax.tagsReturned; //how to access this entityTags in my implementation
}
};
return {
createEntity: create,
getTagsEntity: tags
};
My Implementation
var myEntity = new Entity(url);
myEntity.getTagsEntity();
Ajax call returns object successfully but i am not sure how to access the object inside tags functions in a right way. Any suggestions? This is my first trial to use OO style in JS. Let me also know if i am right track or not.

Function from require() throws undefined error

As a beginner to NodeJS this might be straigtforward but yet I am unable to figure out where I am going wrong
My home.js file is as follow
module.exports = function (deps) {
var sample = require('../lib/sample'), // My own library
express = require('express'),
router = express.Router();
router.get('/', function (req, res) {
op = sample.parse('hi'); // Error here
res.send(op);
});
return router;
};
Under lib folder, my sample.js code is
module.exports = function () {
function parse(text) {
return 'hello' + text;
}
return {
'sample': {
'parse': parse
}
};
};
But I get an error saying undefined is not a function on the highlighted line. Can anyone let me know what I am missing?
Since you export a function, sample will be a function now. You need to explicitly execute it to get the same object. So, you need to do something like this
var sample = require('../lib/sample')().sample
Now, the require statement returns the function, and we immediately execute it, which returns an object with sample property. Since you are interested in sample property only, we get only the sample property.
If you were planning to hide the implementation of parse from the users, I would suggest doing
function parse(text) {
return 'hello' + text;
}
module.exports = {
'parse': parse
};
Now, you are simply exporting the parse function, in an object and the code which requires this module will be able to use parse function, like you mentioned in the question.
Your module.exports evaluates to a function which when called yields the object containing the parse function you are trying to call, under some nesting. You might try restructuring your sample.js file to look like this:
function parse(text) {
return 'hello' + text;
}
module.exports = {
parse: parse
};
Unless you really need the function wrapping shown in your example. In that case you'll have to unwrap it where you import it, so something like this:
var sample = require('../lib/sample')().sample
Change your exports to:
module.exports = function () {
function parse(text) {
return 'hello' + text;
}
return {
'parse': parse
};
};

how to get a property name which represent a function in JS

This is some JS code
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr)
{
window[methodName] = function()
{
console.log(methodName);
}
}
My problem is that how to get the name of a function in JS.
In JS, use this.callee.name.toString() can get the function name. But in this situation, it is a null value. How can i get the 'funName' string?
Sorry, I didn't make it clear.
I want to create functions in a for loop, all these functions has almost the same implementation which need its name. But others can call these functions use different name.I want to know what methodName function is called.
it seems a scope problem.
Try this:
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr) {
var methodName = methodArr[i]; // <---- this line missed in your code?
window[methodName] = (function(methodName) {
return function() {
console.log(methodName);
}
})(methodName);
}
window['secondFunc'](); // output: secondFunc

Categories

Resources