node.js "undefined" mysteriously appears - javascript

I have the following node.js files:
//test.js:
var hash=require('./hash');
var sys=require('sys');
sys.puts(hash.hash("asdf","asdf"));
and
//hash.js:
var exec=require('child_process').exec;
var sys=require('sys');
exports.hash=function(data,hash_type){
exec('pwd',function callback(error,stdout,stderr){
sys.puts(stdout);
});
}
When I do node test.js, I get the following output:
eamorr#Compaq6000:~/Desktop/simple-hash$ node test.js
undefined
/home/hynese/Desktop/nodejs-simple-hash
Why am I getting "undefined"??? I'm really stuck here...
Any help is greatly appreciated.
Many thanks in advance,

Change:
sys.puts(hash.hash("asdf","asdf"));
to just:
hash.hash("asdf","asdf");
You're outputting the return value of hash.hash, although since you didn't provide a return value, the language returns undefined, which is then outputted to the screen. You already output the result of the system command in the callback, so you don't need another sys.puts.
As a side note, you probably don't need to name that callback function callback.

Related

Asserting predicates using Tau Prolog for Javascript

There, I've been trying this issue for over 2 days now and have got nothing to show for it. Therefore, would appreciate some help on this issue.
Issue: Attempting to assert a new predicate using Tau Prolog for Javascript returns a false result. The exact same query results in True when using SWI-Prolog.
The program is taken from a textarea in a HTML page. Everything is local on a single computer only.
**Prolog rules**
<textarea class="example-textinput example-program" id="program">
breads([parmesan, honeywheat]).
</textarea>
**Javascript in the same HTML page**
<script>
var session = pl.create();
var program = document.getElementById("program").value;
session.consult(program);
session.query(`asserta(chosen_meats(variable_to_be_asserted)).`);
session.answers(show())
function show() {
// Return callback function
return function (answer) {
// Valid answer
console.log(answer);
if (pl.type.is_substitution(answer)) {
// Get the value of the food
var output = answer.lookup("X");
console.log(output);
}
};
}
</script>
What I've attempted:
Declaring dynamic predicates in Prolog.
E.g
<textarea class="example-textinput example-program" id="program">
breads([parmesan, honeywheat]).
:- dynamic chosen_meats/1.
</textarea>
Changing to asserta, assertz and assert, when calling the query.
Result: In the callback function show(), false is always getting printed out whenever asserting is attempted.
Term {ref: 6065, id: "throw", args: Array(1), indicator: "throw/1"}
is printed out whenever a query of chosen_meats(X). is done.
However, normal predicate calling such as
session.query("breads(X).");
gives the correct output at
"[parmesan,honeywheat]", when tostring method is used.
Edit: Online Tau Prolog gives the same issue
http://tau-prolog.org/
Error has been expanded as :
error parsing program: error(syntax_error('. or operator expected'), [line(1), column(11), found(client)])
for
:-dynamic client/1.
and
assertz(client(x)).
The syntax error is the clue to the problem, you're missing some parenthesis. Only some Prolog dialects do not require them, so it's best practice to always include them for portability:
:- dynamic(chosen_meats/2).
?- asserta(chosen_meats(chicken, roast)).
true.
I put the solution in the sandbox, query test.: http://tau-prolog.org/sandbox/ZFgsdJkP

Node redis doesn't like function.apply()

I'm trying to wrap a redis client in node but I seem to be having some issues with calling node-redis functions with .apply().
This is causing issues when I tried to do it, which I was able to work around, but now async is calling its functions using .apply() as well which is now causing issues.
Below is a simplification of what I'm doing:
var client = redis.createClient( myOptions );
function set(){
// do other stuff
client.set.apply( null, arguments );
}
However, when I do this I'm getting the following error:
TypeError: Cannot read property 'send_command' of null
at RedisClient.(anonymous function).RedisClient.(anonymous function) (E:\sitesroot\0\node_modules\redis\lib\commands.js:45:24)
The code works perfectly when I pass in the arguments manually like so:
function set( key, value ){
// do stuff
client.set( key, value );
}
This approach won't work though for the likes of wrapping hgetall which has an unspecified number of arguments...
Any insight on what might be causing this?
As #Bergi pointed out in the comment above, you need to pass the correct context when you apply.
client.set.apply( client, arguments );

How to use sendkeys function with promise chaining using selenium webdriverjs?

This is the code:
driver.get(url).then(function(){
txtFnn = driver.findElement(webdriver.By.xpath(xpath));
return txtFnn;
}).then(function(){
txtFnn.sendkeys("12345678");
})
Error:
TypeError: txtFnn.sendkeys is not a function
I'm assuming a lot because you don't supply much info, but from the code, I assume that driver.findElement returns a Promise ... so
driver.get(url).then(function(){
return driver.findElement(webdriver.By.xpath(xpath));
}).then(function(txtFnn){
txtFnn.sendkeys("12345678");
})
Does that work? If so, I'll explain where you went wrong in the first place, but if not, there's no point wasting time on explaining something comes from my assumptions
your code can be simplified as:
driver.get(url);
txtFnn = driver.findElement(webdriver.By.xpath(xpath));
txtFnn.sendkeys("12345678");
can you try this and tell me if you are still getting the error? are you sure that the xpath is correct?

Getting function through AJAX

I was wondering how I can get a function from an AJAX request, like this:
Let's say I have a file called myfunction.js, that looks like this:
function(bar){
alert(bar);
}
Can I retrieve it via Ajax as a function, like this?
var foo = $.ajax({url:'myfunction.js',async:false}).responseText;
And run it like this?
foo(bar);
The reason I ask is because I know responseText is a string,
so I'm not really sure if JavaScript will understand that it is a function.
Is there a way to convert a string into a function?
In your JS file, give the function a name.
function foo(bar){
alert(bar);
}
Then use $.getScript to load it.
$.getScript('myfunction.js', function(){
foo('test');
});
Absolutely:
foo = eval('(' + foo + ')');
foo(bar);
You could use new Function but in my testing it doesn't work on some versions of IE.
I ended up using new Function instead of eval, eval executes the code as soon as it's parsed, which is not what I was after.
This is what I ended up doing, and it works very nicely in firefox, chrome, and IE 7+ (no errors at all)
function createMyFunction(code){return new Function('params',code)};
var thecode = $.ajax({
url: 'myCode.js',
async: false,
dataType: 'html'
}).responseText
myFunction = createMyFunction(thecode);
I know the createMyFunction is pretty lazy in terms of not being able to define different arguments, but using a single params map works for my templating scenario quite well.
Note the dataType:'html' in the ajax request, if you don't specify a plain text mime type, jQuery will actually recognize that you are getting JS code and try to parse it, which generally ends up throwing a parse error or sometimes "Uncaught TypeError: params is not defined".
With this, I am able to have template files that specify template-specific events, and keep them organized in the same way as the markup and css files for that template.
Thanks for the help everyone, the reason I chose the answer that I did is because the link at the end pointed me in the right direction.
Cheers,
D
One thing to beware.
Chrome and IE don't allow you to eval an anonymous function directly (FF is fine). That is
// Throws Syntax Error in Chrome, Object expected in IE 8
var fun = eval('function(){return 5}'); fun();
A hackaround is to put it in an array, doesn't seem very reliable for the future:
var fun = eval('[function (){return 5}][0]'); fun();
The only safe way would be to make sure your functions are named, since the following works fine in all browsers:
eval('function a(){return 5}]'); a(0);
See Are eval() and new Function() the same thing? for further discussion

What triggers "Object cannot be created in this context, Code: 9" in Firefox?

We see this occasionally in web apps on Firefox. What triggers it, and how do we prevent it? It seems to happen sporadically and the error message yields no useful information about line locations.
A quick google search yielded this:
http://blowery.org/2008/02/28/object-cannot-be-created-in-this-context-code-9/
...check your code to see if you’re
trying to grab a reference to the
computed style on a null reference.
It appears to be connected with the Dojo framework.
Edit: Ha. Sorry I gave you your own blog as an answer. I guess I don't completely understand what you're asking for. If you want to avoid the error, you could use object checking before running the applicable code.
function isValidObject(someObject)
{
return typeof someObject != null;
}
var obj1 = "Hello World";
if(isValidObject(obj1))
{
//This code will run
}
if(isValidObject(ob2))
{
//This code will not run
}
Hope that's helpful.

Categories

Resources