in javascript how to call powershell script - javascript

I have a powershell script and I run on powershell like :
.\download-packages-license.ps1
But I want to call the javascript file before these lines.
var json =fs.readFileSync('../../dev/licenses/AllLicenses.json', 'utf8');
var options = {compact: true, ignoreComment: true, spaces: 4};
var result = convert.json2xml(json, options);
I could not anything in stackoverflow except : How to run a powershell script from javascript?
So pls help thanks

I think this will work for you -
var spawn = require("child_process").spawn;
spawn("powershell.exe",[".\download-packages-license.ps1"]);

You can work with : Node-Powershell
Code Snippet :
const Shell = require('node-powershell');
const ps = new Shell({
executionPolicy: 'Bypass',
noProfile: true
});
ps.addCommand('echo node-powershell');
ps.invoke()
.then(output => {
console.log(output);
})
.catch(err => {
console.log(err);
});

JScript
Simple way.
Works great. Suitable for simple operations, but loses some data when receiving line feeds as a single \n instead of the expected \r\n. Split by \r\n misinterprets the array which leads to the need to reformat the array of strings. Basically, I just wrote this, so there may be other problems.
var codepage='windows-1251';/*US-Europe-1252 and Js file in that codepage*/
var toPStext='Hello.\nПроверка русских буковок.';
var shell=new ActiveXObject('WScript.Shell');
var std=shell.Exec("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy Bypass -command \
$OutputEncoding = [Console]::outputEncoding = [System.Text.Encoding]::GetEncoding('"+codepage+"'); \
Write-Output '"+toPStext+"'");
var output = std.StdOut.ReadAll().split('\r\n');// split('\n') - leads to the loss of some data
if (output.length>0){WScript.echo(output)}
//var x=WScript.StdIn.ReadLine();
Line by line.
Unfortunately, powershell does not accept external data as sequences of lines, unlike cmd.exe with /q /k options, which simplifies this code, but will turn around problems with multiline output code. Of course, if necessary, you can transfer the code as a base64 string to powershell
var codepage='windows-1251';/*US-Europe-1252 and Js file in that codepage*/
var toPStext='Hello.\nПроверка русских буковок.';
var shell=new ActiveXObject('WScript.Shell');
var output=[],errors=[],WshRunning=0,WshFinished=1,WshFailed=2,i=0,tryCount=0;
var std=shell.Exec("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy Bypass -command \
$OutputEncoding = [Console]::outputEncoding = [System.Text.Encoding]::GetEncoding('"+codepage+"'); \
Write-Output '"+toPStext+"'");
do{
if (std.Status==WshFailed){
errors.push('String '+i+' data read error: \n '+std.StdErr.ReadLine());
tryCount++
}
else if(std.Status==WshRunning){
output.push(std.StdOut.ReadLine());
tryCount=0;
WScript.Echo('Running ...')
}
else if(std.Status==WshFinished){
var last=std.StdOut.ReadLine();
if(last.length>0){output.push(last)};last=undefined;
tryCount=21;
WScript.Echo('Finished ...')
}i++;
}while(tryCount<21);
if (output.length>0){WScript.echo(output)}
if (errors.length>0){WScript.echo(errors)}
var x=WScript.StdIn.ReadLine();

Related

How to compile a simple Command-line OCaml script into Javascript

I have a simple command line OCaml application that performs a computation on Sys.argv.(1) and outputs the result to stdout. I can compile it to Javascript with js_of_ocaml, but it gives me a lot of errors about caml_ml_output_char being undefined. I fixed those errors by stubbing out the printfs, so it runs, but it freezes firefox while running.
How can I cleanly compile simple OCaml command-line script into a Javascript based webpage; without maintaining a forked version or freezing the browser?
You will probably want to use webworkers, as running software not designed around Javascript's co-operative multi-tasking in the UI thread can cause the browser to lock up.
You can add the following header to the top of your OCaml file to overload the normal OCaml Sys and print implementations
(* JsHeader.ml *)
let output_buffer_ = Buffer.create 1000
let flush x=let module J = Js.Unsafe in let () = J.call
(J.variable "postMessage") (J.variable "self")
[|J.inject (Js.string (Buffer.contents output_buffer_))|]
in Buffer.clear output_buffer_
let print_string = Buffer.add_string output_buffer_
let print_char = Buffer.add_char output_buffer_
let print_newline () = print_char '\n'
let print_endline s = print_string (s^"\n"); flush ()
let caml_ml_output_char = print_char
let printf fmt = Printf.bprintf output_buffer_ fmt
module Printf = struct
include Printf
let printf fmt = Printf.bprintf output_buffer_ fmt
end
The most natural way to pass in commandline arguments is through the URL sent to the web worker. We can override the Ocaml Sys module to instead read ?argv as a sequence of null terminated strings.
module Sys = struct
let char_split delim s = (*Str.split is overkill*)
let hd = ref "" in let l = ref [] in
String.iter (fun c ->
if c = delim
then (l := (!hd)::(!l); hd := "")
else hd := (!hd) ^ (String.make 1 c)
) s;
List.rev ((!hd)::(!l))
let getenv x = List.assoc x Url.Current.arguments
let argv = Array.of_list (char_split '\x00' (getenv "?argv"))
let executable_name = argv.(0)
end
Now that we have entered the header we can enter a simple OCaml Command Line program:
(* cli.ml *)
let _ = print_string (Array.fold_left (^) "" (Array.make 40 (String.lowercase (Sys.argv.(1)^"\n"))) )
This command line program relies on the OS to flush the output, but we will have to manually flush the output.
You may also want to send a null character so the Javascript knows that the command has finished.
This can be achieved by appending the following footer.
(* JsFooter.ml *)
let _ = flush stdout; print_endline "\x00"
We can join the files and compile them as follows:
cat JsHeader.ml cli.ml JsFooter.ml > merged.ml
ocamlbuild -use-menhir -menhir "menhir" \
-pp "camlp4o -I /opt/local/lib/ocaml/site-lib js_of_ocaml/pa_js.cmo" \
-cflags -I,+js_of_ocaml,-I,+site-lib/js_of_ocaml -libs js_of_ocaml \
-lflags -I,+js_of_ocaml,-I,+site-lib/js_of_ocaml merged.byte
js_of_ocaml merged.byte
Now that we have created the file merged.js we can wrap the javascript in a simple web page such as the following:
<html>
<head>
<meta http-equiv="Content-Type" content="text/xhtml+xml; charset=UTF-8" />
<title>ml2js sample_cli</title>
<script type="text/javascript">
<!--
var worker;
function go () {
var output=document.getElementById ("output");
var argv = encodeURIComponent("/bin/sample_cli\0"+document.getElementById ("input").value);
if (worker) {
worker.terminate();
}
worker = new Worker ("sample_cli.js?argv="+argv);
document.getElementById ("output").value="";
worker.onmessage = function (m) {
if (typeof m.data == 'string') {
if (m.data == "\0\n") {
output.scrollTop = output.scrollHeight
} else {
output.value+=m.data;
}
}
}
}
//-->
</script>
</head>
<body onload=go()>
<textarea id="input" rows="2" cols="60" onkeyup="go()" onchange="go()" style="width:90%">SAMPLE_INPUT</textarea>
<button onclick="go()">go</button><br>
<textarea id="output" rows="0" cols="60" style="width:100%;height:90%" readonly onload=go()>
Your browser does not seem to support Webworkers.
Try Firefox, Chrome or IE10+.
</textarea>
</body>
</html>
See http://www.dansted.org/app/bctl-plain.html for an example of this approach in action, and https://github.com/gmatht/TimeLogicUnify/blob/master/ATL/js/webworker/ml2js.sh for a script that appends the appropriate headers, footers etc.
What js_of_ocaml's version are you using ? You should not get errors with caml_ml_output_char. When running on node, you should have sys.argv set correctly. In the browser, Sys.argv is set to [|"a.out"|].
Please open a GitHub issue on https://github.com/ocsigen/js_of_ocaml/issues/new if you still have an issue with this.

Parsing a Javascript object from online resource

I'm attempting to parse a Javscript object online using nodejs.
This file for example: http://www.google.com/recaptcha/api/challenge?k=6Leluc8SAAAAAElzN1CrcweqVxkUfmGa7QC40pUU
This is not JSON, and is regular JavaScript. I have managed to parse out the JavaScript object using:
/* Data is the JS file above */
var j = data.substring(data.indexOf('{'), data.indexOf('}') + 1);
But, how do I parse that so I can read it as an object? JSON.parse doesn't work because its not JSON formatted.
Edit
As the challenge key is what I require, I ended up solving it with substring and indexOf:
var start = data.indexOf('\'');
var end = data.substring(start + 1).indexOf('\'');
var challenge = data.substring(start, (start + end) + 1);
But I'd still like to know a solution to the origional problem. And yes, I could use "'" but in this project we stuck to using single quotes and I'm a stickler for making sure everything is in line with the style guide. Silly I know, just a habbit.
well the simplest way is the following for this particular issue.
var x = JSON.stringify({
challenge : '03AHJ_VuuiaIB_izO6VJ6PifXI8A8i1yBeG6biCjadtaZHk5pbxfbW5JPpEXBEay-LPdCzSOI1bQgdnjq1tQVSqzQ63hMQB1Sjlho4LdzfZKLXuK3TKZD1YPr5bIjM-dYqHIkcYpaanchXOXLkHNoj0B6_ZrUk4rZg-o790H1LMNzoPGy3qkk6suYWs1CERFjkTO_mw9puMnYQNITPzBnRS-QMilbch2d_PeM2aDGToLSQiLn8mgHwP7fUHvCcE9VGzNZNXkDC8wF-YvUCxU354VqeSa8U7KKycg',
timeout : 1800,
lang : 'en',
server : 'http://www.google.com/recaptcha/api/',
site : '6Leluc8SAAAAAElzN1CrcweqVxkUfmGa7QC40pUU',
error_message :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jam1ncnRRcWQxaHRUeVlVMEJoTGFuRE5sSEtTdUp0UVlqQVl4MzN1UnZsZE8yQTA1cEpHdUd0UDRNQkhjTmFEUlV0WTNyamhOUnBnNDB2RndVNHZWSFVRVWZCVGdJNXNJY2pCOUlVUytpVWQ3VFg5ZUxhSnpaV3hGR2pRWm9JRVN3b0NrWlAwNnVKTmV1VGpMa3htWXBQcCtyVXpqdG5IU0Y4Q3ZhdWhtSkxsTVZyeEQxb3RDSXAzWkUxd0ZXVG9WV000Qjh5NlA2ZzB2ajJqSWw1RitYeG5RZzZaNVdqS1A3UjhGaWJMOVpNNEZMR1VoTzdlTWRzU1YxK1VNQytzZFJrVnM1ZjYyVys0T2Jld3FacTI3Qy8wdDJ4NEYrUG16QU92alpqcG1KbnI5RU5WZGZMVk1VZGNJeUJiMVhuVHJrRWw3UnNRQkxsa1FPOHM0cEt4eDdYazNTeCt6NGcxTm8xY1pXaHFWdFZ5bklkOXYxdU9jVklBYUE9'
});
console.log(JSON.parse(x).challenge);
//03AHJ_VuuiaIB_izO6VJ6PifXI8A8i1yBeG6biCjadtaZHk5pbxfbW5JPpEXBEay-LPdCzSOI1bQgdnjq1tQVSqzQ63hMQB1Sjlho4LdzfZKLXuK3TKZD1YPr5bIjM-dYqHIkcYpaanchXOXLkHNoj0B6_ZrUk4rZg-o790H1LMNzoPGy3qkk6suYWs1CERFjkTO_mw9puMnYQNITPzBnRS-QMilbch2d_PeM2aDGToLSQiLn8mgHwP7fUHvCcE9VGzNZNXkDC8wF-YvUCxU354VqeSa8U7KKycg
In the browser
This should work on client-side JavaScript :
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "http://www.google.com/recaptcha/api/challenge?k=6Leluc8SAAAAAElzN1CrcweqVxkUfmGa7QC40pUU";
document.body.appendChild(js);
It adds the external file to your HTML. The JavaScript inside is run once it's been loaded.
Node.js
In node, I'd take this road :
Do an HTTP request to get the code
Save that code as a text file
require the file you just saved
If you take that road, your code should look something like this :
require("request")("http://www.google.com/recaptcha/api/challenge?k=6Leluc8SAAAAAElzN1CrcweqVxkUfmGa7QC40pUU", function(error, response, body) {
require('fs').writeFile('./stuff.js', body, function(err) {
if(err) {
return console.log(err);
}
var stuffIJustLoaded = require('./stuff.js');
});
});

write file with "\n" with node.js

Im working with a lot of datas which i turned into arrays , for simplicity lets assume i have array that looks like this
["dataone:dataone","datatwo:datatwo","datathree:datathree"]
im writting output to the file using fs.writeFile
but the output is always in the same row e.g dataone:dataone","datatwo:datatwo","datathree:datathree
i would like to output to be like with "\n" e.g
dataone:dataone
datatwo:datatwo
datathree:datathree
is it possible to make output in file look like this? im writting in into .txt file
Join the data with line breaks before writing to file
var os = require('os');
var brk = os.platform().substring(0,3).toLowerCasee() === 'win'
? '\r\n' : '\n';
var data = ["dataone:dataone","datatwo:datatwo","datathree:datathree"]
fs.writeFile(filename, data.join(brk), {encoding : 'utf8'}, function (e) {
// etc
});
You can join your array with \n before writing it to the file:
var arr = ["dataone:dataone","datatwo:datatwo","datathree:datathree"]
var arr2 = arr.join('\n');

replace carriage return and new line from sql server in javascript

I've got varchar data from SQL Server returned to javascript as JSON where I'm trying to remove carriage return + linefeed with br. When I query my data in SQL Server I can see I have CHAR(13)CHAR(10) characters. My javascript code I've tried is below: (taEmail is a dijit/form/SimpleTextarea):
var data = this.taEmail.get("value");
var regxp = /\r\n/g;
var data2 = data.replace(regxp, "<br\>");
also tried:
var data = this.taEmail.get("value");
var data2 = data.replace("CHAR(13)(CHAR(10)", "<br\>");
Any ideas how I can make this work? I suppose I could do it on the SQL server end, but would prefer javascript
Thanks
I did a simple test in the console window of the browser and it works.
below is my code.
var data = "line end\r\n";
/*
console output for data >>>
"line end
"
*/
var data1 = data.replace(/\r\n/g,"<br>");
/*
console output for data1 >>>
"line end<br>"
*/

Parsing JSON stream

I have an application that is using chrome.sockets. JSON is being passed to and from the socket which does not have a delimiter and is not prefixed with the length of the string.
Now the way sockets are read in chrome.sockets is by passing a max buffer length and it will read all available bytes until the buffer is full. The documentation for the socket.read can be found here
Short of writing/porting a parser, is there a JavaScript JSON parser where I can simply pipe in the response from socket.read?
Have you seen https://github.com/creationix/jsonparse? Looks like it assumes a Node.js environment, but it doesn't like it would be hard to tweak the API to meet your needs.
Update: As you need to check that the JS is valid, you could use JSON.parse to check if it's valid JSON, this should always be available in Chrome. You can convert your arraybuffer to a string and append it on to an accumulator string and after each iteration perform the following check on that string.
function isValidJSON(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
};
// assuming 16bit uint unicode chars
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
Below is an example callback function you could use:
jsonData = "";
function readJSONFromSocket(object readInfo) {
// Arraybuffer to string
partialJSONData = ab2str(readInfo.data);
// Loop through the chars until we get a valid JSON object
for (var x = 0; x < partialJSONData.length; x++) {
// Build up the JSON character by character
jsonData += partialJSONData.charAt(x);
if (isValidJSON(jsonData)) {
console.log(jsonData);
// Do something here
jsonData = "";
}
}
};
I know this question was posted a while ago but here is a good way to handle this.
Install Node JS, install NPM (Node Package Manager)
npm install -g browserify
npm install -g JSONStream
echo "window.JSONStream = require('JSONStream');" > script.js
browserify script.js jsonstream.js
in your webpage
var parseStream = new JSONStream('*');
while (var buffer = socket.read()) {
parseStream.write(buffer);
}
parseStream.on('data', function (obj) {
// obj is a parsed obj
})
Now if you want pipe methodology because your a fan of unix. then add
npm install shoe
shoe('./socketName').pipe(parseStream);

Categories

Resources