I am new to node.js and I have a simple function which takes to parameters and returns the result of adding those to up:
function DoMath(p1, p2) {
try {
return p1 + p2;
} catch (exception) {
return "sorry, worng output do you want to try again?"
}
}
This function is located it the file app.js.
I also added export of the function: module.exports.DoMath=addTowPharmetrs;
In other file, called app2.js, i am trying to give to parameters to the function and call it:
var key=require("./app.js");
var output=key.addTowPharmetrs(5, 1);
/*expected output: 6*/
console.log(output);
However, the program is not running with the error:
ReferenceError: addTowPharmetrs is not defined
What should I do in order to fix it and make it work?
You mixed up the property name with the local variable name:
module.exports.DoMath=addTowPharmetrs;
should be
module.exports.addTowPharmetrs = DoMath;
Related
I have a program which compiles js from ajax requests with the new Function(), and I am trying to know from which file the error originated, I have tried to
var f = new Function(code);
Object.defineProperty(f, "name", {writable:true});
f.name = 'myFuncName';
But still when an error happens it shows anonymos:2:3
I have also tried to do this
try {
var f = new Function(code);
}catch(e){
console.log(e)
}
But the error doesn't get catched, I think is because the code inside the function is async
Any ideas?
you can try with
var f = function myFuncName (){
return (new Function(code))
.apply(this, arguments)
};
I have a javascript file I want to call. contents are below. When I tried calling the file, I keep getting a "no variable found with name: response" even though there is clearly a variable defined. The file executes fine within command-line using node so the javascript function is valid. Any thoughts? I attached the error message in a screenshot.
Javascript content in snippet below.
Karate script:
Scenario: Call JavaScript:
* def sample = read('classpath:reusable/gen-data.js')
* print someValue
function createTestData(sampleJson, fieldsToChange, numRecords) {
var testData = [];
for (var i = 0; i < numRecords; i++) {
var copy = JSON.parse(JSON.stringify(sampleJson));
fieldsToChange.forEach(function(fieldToChange) {
copy[fieldToChange] = copy[fieldToChange] + i;
});
testData.push(copy);
}
return {content: testData};
}
var testData = {
"country": "US",
"taskStatusCode" : "Closed",
"facilityCode" : "US_203532",
};
function getTestData() {
String testData = JSON.stringify(createTestData(testData, ["taskStatusCode", "facilityCode"], 1), null, 1);
console.log("all done getTestData()");
console.log("test data: \n" + testData);
return testData;
};
console.log("calling getTestData()");
getTestData();
I think this error is thrown when the JavaScript is not correct. For example in my case this JS file:
/* Set the custom authentication header */
function fn() {
var authToken = karate.get('authToken');
var out = {};
out['Auth-Token'] = authToken
return out;
}
This file will produce the "no variable found with name: response".
The reason is because "the right-hand-side (or contents of the *.js file if applicable) should begin with the function keyword." according to the karate docs (link).
Now by moving the comment and making the function keyword the first bit of text it works as expected:
function fn() {
/* Set the custom authentication header */
var authToken = karate.get('authToken');
var out = {};
out['Auth-Token'] = authToken
return out;
}
In the OP, the function keyword is the first thing in the file, but there is javascript outside the original function -- which I don't think is legal for karate syntax. In other words, everything has to be in the outer function.
My workaround was to use java instead of JavaScript.
I have tried for a couple of days researching on how to create a custom exception in a try/catch.
Here is what I am attempting to do:
I have an included JS file in my html page. The JS file defines a custom object, as well as defining methods for the object.
Next, in the html page I am doing the following:
try {
MyObj = new CustomObj; //from the included JS file.
MyObj.CustomMethod(); //also from the included JS file.
} catch(e) {
alert("Error in either the create of the object, or the method. Error is " + e.description)
}
I need to be able, within the code for the CustomMethod(), to set the Error Object's properties that are captured in the catch statement. For example:
CustomMethod = function{
try{
document.getelementById("field1").value = "my value";
} catch(err) {
//Set the return error
ReturnErr.description = "There was an error!";
}
};
Can this be done? From what I have tried, I have used the throw statement, but it does not effect the Error Object, thus the catch section is never triggered. In face, the custom message is only shown in the Console.
Thanks ahead of time.
Try:
function MyException(_message, _data) {
this.message = _message;
this.data = _data;
this.name = "MyException";
}
Usage
try{
//...
}
catch(_error){
throw new MyException(message, _error);
}
Hope it will help you to sort things out
I have written a javascript function which will get executed inside db.eval() on mongodb on my nodejs platform.
my js function is:
function(data){
var d = {
vehicle_id:data.vehicle_id,
timestamp:{
$gte:data.start_time,
$lte:data.end_time
}
};
var routeStatus = [];
db.location.find(d,function(err,result){
db.result.insert({result});
});
}
which is minified to an string 'code' to be passed to db.eval()
var code = 'function(data){var d={vehicle_id:data.vehicle_id, timestamp:{$gte:data.start_time, $lte:data.end_time}}; db.location.find(d,function(err,result){return result;});}';
db.eval(code,[info],function(err,result){
log(result);
});
the info object contains all required fields getting called by function;
Now main question is db.location.find() is an asynch call so how could i get its result return to callback of db.eval(); ?
if i simply do return result from callback of db.location.find() then i get nothing returned as its being an async call.
got the answer, thanks to #NeilLunn for giving small but useful tip. the .toArray() worked
simple doing
var docs = db.location.find().toArray();
worked for me.
I have made a following custom logs function to print all console log messages. Using this function I can control with a single flag variable to either print or not logs throughout the app.
var Utilities = {
showLogs: true,
printLog: function (msg) {
if (this.showLogs) {
console.log(msg);
}
}
};
and I call it as:
Utilities.printLog("a message to print on console");
It works fine as expected. But it has one limitation i.e. its not showing the correct line no# and file name where this was called to print the logs.
One solution is to provide extra parameters to print line no# & file name along with the message.
for instance:
Utilities.printLog("a message to print on console", "10","common.js");
Utilities.printLog("a message to print on console", "310","myLib.js");
I dont want these extra parameters and like to know if there is another option available.
Update:
I tried the V8's Stack Trace API http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi but it only helps in cases when an exception is generated inside try catch block.
First override the Error.prepareStackTrace and create a tracing function like this:
Error.prepareStackTrace = function(error, stack) {
return stack;
};
function getTrace(e) {
var stack = e.stack;
var trace = "";
for (var i = 0; i < stack.length; i++) {
trace += "\r" + stack[i];
}
return trace;
}
and created two sample js files.
libObj.js
var libObj = {
getCube: function(x){
return mathLib.cube( x );
}
};
mathLib.js
var mathLib = {
cube: function(x){
return evilObj * x * x; //see the undefined evilObj --- lets catch trace here
}
};
Now from a third js file (or in my case inside the HTML file) I call the function within the try catch block to see the precise trace of the vulnerable code.
<script type="text/javascript">
try {
var results;
results = libObj.getCube(2);
console.log( results );
} catch (e) {
console.log( getTrace(e));
}
</script>
Now I get below trace of the vulnerable code:
Note:- If you do not override the Error.prepareStackTrace then it gives, I think pretty formatted trace...though both have same info.
Without overriding Error.prepareStackTrace:
Now the question remains open, how I can capture similar trace for my custom logs function as defined above.
You could do this:
var Utilities=
{
showLogs:true,
printLog:function(msg){
if(!this.showLogs) return 0;
var k=new Error().stack.split("\n").slice(2);
k.unshift(msg);
console.log(k.join("\n"));
}
}