I have the following javascript:
#!/usr/bin/env node
var fs = require(’fs’);
var outfile = "hello.txt";
var out = "Modify this script to write out something different.\n";
fs.writeFileSync(outfile, out);
console.log("Script: " + __filename + "\nWrote: " + out + "To: " + outfile);
on executing the following commands:
node test.js
cat hello.txt
i get the following output:
[object Object]
What am i doing wrong?
Your getting an object returned as a string. Your going to need find out what properties the object has and return them, or loop through the object and show the properties, or convert it to a string...
console.log(JSON.stringify(objToJson));
Related
I am trying to include variable inside cmd /c runas command, I use JS function and it gives me an error that specified file was not found.
I guess I am using the wrong variable calling or something.
Here is my function:
function runasSRVhta(){
var WShell = new ActiveXObject('WScript.Shell');
// var srvDude = document.getElementById("SRVinput").value;
var SRVguy = "someadmin.srv";
WShell.Run('cmd /c runas /u:sa.local\\SRVguy "c:\\windows\\system32\\mshta.exe """\\\\fs\\FIle Share\\SA Support\\ZverTools\\giveMeIPsPLZ.hta""""', 1, true);
}
Instead of running following command as someadmin.srv it runs its variable name, without taking value.
Problem is here - cmd /c runas /u:sa.local\\SRVguy, SRVguy should be variable taken from var SRVguy = "someadmin.srv";
Update
I tried following function as well, it detects variable value, but my HTA gives me another error saying that it can't find the file specified.
function testsrv() {
var shell = new ActiveXObject("WScript.Shell");
var SRVguy = "someadmin.srv";
var SRVguyaftertext = 'c:\\windows\\system32\\mshta.exe """\\\\fs\\FIle Share\\SA Support\\ZverTools\\giveMeIPsPLZ.hta"""';
var satavesrv = 'cmd /c runas /u:sa.local\\';
var theend = "'" + satavesrv + SRVguy + ' "' + SRVguyaftertext + '"' + "'";
document.write(theend);
var path = theend;
shell.run(theend,1,false);
}
Oh, and I used document.write to check output if it is correct, here is the output:
'cmd /c runas /u:sa.local\someadmin.srv "c:\windows\system32\mshta.exe """\\fs\FIle Share\SA Support\ZverTools\giveMeIPsPLZ.hta""""'
Everything seems correct with second function, but HTA pops up an error message saying that it cannot find the file specified...
try using template strings to include the variable in the string like this
WShell.Run(`cmd /c runas /u:sa.local\\${SRVguy} "c:\\windows\\system32\\mshta.exe """\\\\fs\\FIle Share\\SA Support\\ZverTools\\giveMeIPsPLZ.hta""""`, 1, true);
- Update
WShell.Run('cmd /c runas /u:sa.local\\' +SRVguy + ' "c:\\windows\\system32\\mshta.exe """\\\\fs\\FIle Share\\SA Support\\ZverTools\\giveMeIPsPLZ.hta"""', 1, true);
Line break in javascipt string console
console.log("Foo" + "\n" + "Bar");
Line break in javascript object console
console.log({ value : "Foo\nBar" });
Is it possible to add linebreaks in javascript objects.
The answer is no: when you print an object to the console log, strings will be written as javascript objects (similar but not identical to what you'd get if you explicitly converted them into JSON, like console.log(JSON.stringify(object))).
If you want for some reason to print your strings with line breaks, you'd have to implement the object-to-string conversion yourself; perhaps with something like this:
function customString(object) {
let string = '{\n';
Object.keys(object).forEach(key => {
string += ' "' + key + '": "' + object[key] + '"\n';
});
string += '}';
return string;
}
console.log(customString({ value: "Foo\nBar" }));
(It sounds like you have an idea in mind of exactly how you want this output to look, so adjust the function above until it works as expected.)
You can make JSON pretty with automatic line breaks using:
console.log(JSON.stringify({ test: { key: { inner: 'val' } }}, null , 2))
Where 2 is the number of spaces/indent for each level.
You can use ES6:
console.log(`hello
world`)
will produce:
hello
world
I think its originally creating a line break, but due to the object, it's not showing directly. Try to assign it in variable and access that in the console.
Code:
var v = {val:"test\ntest"};
console.log(v.val);
Output:
test
test
I am trying to load a javascript in WebView to do some calculations and get the output in a string. I tried to use following code
string htmlFragment = "<html><head><script type='text/javascript'>" +
"function doubleIt(incoming){ " +
" var intIncoming = parseInt(incoming, 10);" +
" var doubled = intIncoming * 2;" +
" document.body.style.fontSize= doubled.toString() + 'px';" +
" return doubled.toString());" +
"};" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
htmlView.NavigateToString(htmlFragment);
htmlView.LoadCompleted += async(s1,e1) =>
{
string result = await htmlView.InvokeScriptAsync("eval", new string[] { "doubleIt(25)" });
Debug.WriteLine(result);
};
Update
I am able to load simple javascript easily now based on help provided in the answer. But now I am facing issues when there is more than one function in javascript, I am getting an exception. I am trying the following code
string htmlFragment = #"<html><head><script type='text/javascript'>" +
"function a(){return 10;};" +
"function b(){return 20;};" +
"function c(){return 30;};" +
"return (a()*b()*c());" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
Please suggest.
The documentation for this feature is really poor. It took me some time to figure out how to invoke Javascript in UWP WebView
When you first look at the function call webView.InvokeScriptAsync(string,string[]) your initial reaction is that they want the function name as the first parameter and then the function paramaeters as the string array. (mainly because the MSDN documentation says this)
Parameters
scriptName
Type: System.String [.NET] | Platform::String [C++]
The name of the script function to invoke.
arguments
Type: System.String[]
[.NET] | Platform::Array [C++]
A string array that
packages arguments to the script function.
HOWEVER, this is wrong and will lead to hours of head banging. REALLY, what they want is the word "eval" in the first parameter and then a string array of functions, and or commands you wish to eval
var value = await webViewer.InvokeScriptAsync("eval",
new string[]
{
"functionName(functionParams)"
});
Having worked with Microsoft APIs for a few years now I am convinced that this is not the intended way of consuming this function and is a bit of a hack. Unfortunately if you want to consume JavaScript this is the only way that I know that works currently.
Anthony,
Try to check your own suggestion:
await webViewer.InvokeScriptAsync("eval",
new string[]
{
"functionName(functionParams)"
});
or:
await webViewer.InvokeScriptAsync(functionName, new string[]{ functionParameters });
The same as Microsoft suggests, just you are limiting a function name by one ("eval") - not necessary. Trust me, you can use any function name, as I am now with UWP and before with windows phone hybrid apps.
The question is already 4 years old, but I'm coming to see why you were getting an empty string as a result.
In your example, the functions in JavaScript return integers while the expected value is of type string.
By modifying these functions and returning a string like this:
string htmlFragment = #"<html><head><script type='text/javascript'>" +
"function a(){return '10';};" +
"function b(){return '20';};" +
"function c(){return '30';};" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
We get the good result on the way back.
everybody. I've just integrated duktape in my c++ code so that I'm able to use javascript.
But the problem I can't solve right now : how to use json objects in javascript.
Assume I've got some javascript like
function hi(person) {
print ('hi, ' + person.name );
}
And json object :
{
'name' : 'duktape'
}
So now I need to call function hi with an argument of this json in my cpp code.
duk_eval_string(ctx, "function hi(person) {print ('hi, ' + person.name );}");
duk_push_global_object(ctx);
duk_get_prop_string(ctx, -1, "hi" ); // pushes function from loaded script to stack
auto json = "{'name' : 'duktape' }";
duk_push_string(ctx, json);
duk_pcall(ctx, 1);
The output I get tells, that object is not correct
hi, undefined
Would like to head any suggestions on who should be done to get it working! Thank's for your time :)
You need to use duk_json_decode:
char *json = "{\"name\": \"duktape\"}";
duk_push_string(ctx, json);
duk_json_decode(ctx, -1);
duk_pcall(ctx, 1);
duk_pop_2(ctx);
Output:
hi, duktape
Note that your original json is not valid, you need to use " as string delimiters instead of '.
Depending on what you really needs, you could also create the object manually:
duk_idx_t obj_idx = duk_push_object(ctx);
duk_push_string(ctx, "duktape");
duk_put_prop_string(ctx, obj_idx, "name");
duk_pcall(ctx, 1);
duk_pop(ctx);
I try to parse an XML string and have some problems. Here is my current state.
I have a Cordova app which reads QR-Codes (with the BarcodeScanner plugin). The QR-Code holds the XML information. When I read the code, I want to print out the XML code. Here is what I tried (the important part):
var app = {
output: null,
xmlDoc: null,
// this function is called when I click a button
scanCode: function(){
//first parameter is a callback, which is called when a barcode is detected
cordova.plugins.barcodeScanner.scan(
function (result) {
alert(result.text);
var parser = new DOMParser();
**app.xmlDoc = parser.parseFromString(result.text,"text/xml");**
app.output = document.getElementById("codeInfo");
app.traverse(app.xmlDoc.documentElement, "");
},
function (error) {
alert("Scanning failed: " + error);
}
);
},
traverse: function(node, offset){
if(node.nodeType == 3){
app.output.innerHTML += "<b>" + offset + node.nodeValue + "</b><br>";
}else{
app.output.innerHTML += offset + node.nodeName + "<br>";
var childs = node.childNodes;
for(var i=0; i<childs.length; i++){
app.traverse(childs[i], offset + " ");
}
}
}
};
My XML code looks something like this
<node><child1>text1</child1><child2>text2</child2></node>
So I expect an output like:
node
child1
text1
child2
text2
But I always get something like:
html
body
parsererror
h3
This page contains the following errors:
...
When I use a static text like
var xml = "<node><child1>text1</child1><child2>text2</child2></node>"
and use this instead of 'result.text' in the marked line, everything works as expected.
So maybe the 'result.text' is just a reference and not the value? Could this be the problem? I'm not an expert so how can I solve this problem?
P.S.: The XML code I get from the QR-Code is correct and well formed.
app.xmlDoc = parser.parseFromString(result.txt,"text/xml");
should actually be:
app.xmlDoc = parser.parseFromString(result.text,"text/xml");
There is an "e" missing in result.text
After reading Valencia's comment and the "wrong" output again and think about it, I figured out what's wrong. So the "wrong" output is just an error message in HTML format, where i print every tag. The message itself says:
This page contains the following errors:
error on line 1 at column 14: String not started expectin ' or "
The beginning should look like this
<?xml version="1.0" encoding="UTF-8"?>
but when creating the QR-Code backslashes are added
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
The first backslash is at column 14.
When I create a static XML string I insert backslashes to mask the ' " ', so my declaration and the XML code from the QR-Code look equal. But they aren't, cause the static XML string does not contain the backslashes. And these backslashes cause the error while parsing.
The easiest solution is to just not put the XML information in the QR-Code. So directly starting with the first node.
Thanks for your help.