how do we convert following vbscript to javascript?
<script type="text/vbscript">
Function SayHello()
MsgBox "Hello"
HKEY_LOCAL_MACHINE = "&H80000002"
uninstallRegKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
stdRegPro = "winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\default:StdRegProv"
Set objReg=GetObject(stdRegPro)
objReg.EnumKey HKEY_LOCAL_MACHINE, uninstallRegKey, arrSubKeys
MsgBox arrSubKeys
End Function
</script>
Any help appreciated.
Thanks,
Lok.
You can, if you use JScript (Microsoft's implementation of Javascript for Windows) and some information e.g.
Calling WMI Methods with JScript
Troubles with WMI in JScript
(found by googling "jscript wmi").
Evidence:
function showUnInstall() {
var HKEY_LOCAL_MACHINE = 0x80000002;
var uninstallRegKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
var stdRegPro = "winmgmts:{impersonationLevel=impersonate}!//./root/default:StdRegProv";
var objReg = GetObject(stdRegPro);
var mEnumKey = objReg.Methods_.Item("EnumKey");
var ipEnumKey = mEnumKey.InParameters.SpawnInstance_();
ipEnumKey.hDefKey = HKEY_LOCAL_MACHINE;
ipEnumKey.sSubKeyName = uninstallRegKey;
var mGetStringValue = objReg.Methods_.Item("GetStringValue");
var ipGetStringValue = mGetStringValue.InParameters.SpawnInstance_();
ipGetStringValue.hDefKey = HKEY_LOCAL_MACHINE;
ipGetStringValue.sValueName = "DisplayName";
var opEnumKey = objReg.ExecMethod_(mEnumKey.name, ipEnumKey);
if (0 === opEnumKey.ReturnValue) {
var aNames = opEnumKey.sNames.toArray();
for ( var i = 0; i < aNames.length; ++i) {
ipGetStringValue.sSubKeyName = uninstallRegKey + "\\" + aNames[i];
var opGetStringValue = objReg.ExecMethod_(mGetStringValue.name, ipGetStringValue);
if (0 === opGetStringValue.ReturnValue) {
WScript.Echo(opGetStringValue.sValue);
} else {
WScript.Echo("ERROR: GetStringValue.ReturnValue =", opGetStringValue.ReturnValue);
}
}
} else {
WScript.Echo("ERROR: EnumKey.ReturnValue =", opEnumKey.ReturnValue);
}
}
output:
cscript 26907078.js
7-Zip 4.65
ActiveState ActiveTcl 8.5.2.0
ERROR: GetStringValue.ReturnValue = 1
Adobe Flash Player 15 Plugin
ERROR: GetStringValue.ReturnValue = 1
CMake 2.8, a cross-platform, open-source build system
Acrobat.com
...
You can't. Javascript does not have access to the registry.
This is not entirely accurate, I remember. A Node.js webserver running on Windows with NPM tools does have access, but only to that on the server it's running on. however, client-side javascript does not have access to the registry.
Related
Hello and to a very happy and more healthy 2021!
I am setting up a small communication interface between a JS client and a AS3 Server based on the Websockets protocol.
For various reasons I need to compress and base64 encode the payloads.
From AS3 to JS everything works like this (using https://github.com/blooddy/blooddy_crypto to handle the Base64 en/decryption ) :
function encodeMessage(message:String):String{
var rawData:ByteArray=new ByteArray()
rawData.writeUTFBytes( encodeURIComponent(message) );
rawData.compress();
var b64 = Base64.encode(rawData);
return b64;
};
decoding in JS with pako for inflation (https://github.com/nodeca/pako):
decodePayload(payload){
let rawfile = (atob(payload));
var bytes = [];
for (var fileidx = 0; fileidx < rawfile.length; fileidx++) {
var abyte = rawfile.charCodeAt(fileidx) & 0xff;
bytes.push(abyte);
}
var plain = pako.inflate(bytes);
var enc = "";
for (var i = 0; i < plain.length; i++) {
enc += String.fromCharCode(plain[i]);
}
return decodeURIComponent(enc);
}
now the other direction creates some problems:
in JS I use:
encodeMessage(message){
let enc = encodeURIComponent(message)
let zlib = pako.deflate(enc)
let b64 = btoa(zlib);
return b64;
}
but then I am running into issues on the AS3 side:
function decodePayload(payload:String){
var ba:ByteArray = Base64.decode(payload);
//this is where the error happens
ba.uncompress();
}
the error is a "Error: Error #2058: There was an error decompressing the data."
I suspect that the bytearry i receive from pako.deflate is different from what AS3 is using?
Any pointers welcome!
here is the solution - a stupid little oversight of course ;)
in the encode function in JS the Uint8Array needs to be converted into a BinaryString before it gets Base64 encoded:
function encodeMessage(message){
let enc = encodeURIComponent(message);
let zlib = pako.deflate(enc);
let binstring = convertUint8ArrayToBinaryString(zlib);
let b64 = btoa(binstring);
return b64;
};
function convertUint8ArrayToBinaryString(u8Array) {
var i, len = u8Array.length, b_str = "";
for (i=0; i<len; i++) {
b_str += String.fromCharCode(u8Array[i]);
}
return b_str;
}
Then all is well in Roswell.
It's not obvious if your AS3 code is used in just an SWF file or you have an AIR project.
If making an AIR project:
Try using uncompress.apply... (code not yet tested).
//# this is where the error happens
//ba.uncompress();
//# try this..
ba.uncompress.apply(ba, ["deflate"]);
If making an SWF project:
When I needed Deflate algorithm inside an SWF running on browser I used a port of Zlib.
Get as3zlib at: https://github.com/BenV/as3zlib (is a port of Zlib for Java).
note: While in JS it's better to make local vars rather than global, this a quirk of JavaScript
and actually in most C-like languages (Java, C#, AS3, etc) this is opposite, a global variable is less expensive than constantly making local vars every time the function is called.
Here is a usage example:
//# import Zlib Class
import Zlib;
//# setup global vars
var zlibdecomp :Zlib;
var ba :ByteArray = new ByteArray;
var decoded_BA :ByteArray = new ByteArray;
//# try Deflate algo...
function decodePayload(payload:String)
{
zlibdecomp = new Zlib;
ba.clear(); //in case it already has data from a prev decode
//# all code below can be done in this one line
//ba = zlibdecomp.uncompress( Base64.decode(payload) );
ba = Base64.decode(payload);
//# this is where the error happens...
//ba.uncompress();
//# try this...
decoded_BA = zlibdecomp.uncompress( ba ); //inflate to original big from small/compressed
//ba = decoded_BA; //if this way of updating is needed
}
I tried searching . How do i do it? I'm create html and i want to read .ini file by javascript on the client Not in the server.
I copy code from javascript parser for a string which contains .ini data
error Uncaught ReferenceError: require is not defined var fs = require('fs')
function parseINIString() {
var fs = require('fs')
var data = fs.readFileSync('C:\\test.ini', 'utf8');
var regex = {
section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
param: /^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/,
comment: /^\s*;.*$/
};
var value = {};
var lines = data.split(/\r\n|\r|\n/);
var section = null;
alert(lines);
for (x = 0; x < lines.length; x++) {
if (regex.comment.test(lines[x])) {
return;
} else if (regex.param.test(lines[x])) {
var match = lines[x].match(regex.param);
if (section) {
value[section][match[1]] = match[2];
} else {
value[match[1]] = match[2];
}
} else if (regex.section.test(lines[x])) {
var match = lines[x].match(regex.section);
value[match[1]] = {};
section = match[1];
} else if (lines.length == 0 && section) {//changed line to lines to fix bug.
section = null;
};
}
return value;
}
Let's say the javascript running in a browser is so called 'client script'. There are lots of limitation while writing client script, one of them is that it's not allowed to visit the user file on disk. This is to prevent any injected hacker script from reading private data. And the explicit error you see is about the new key word 'require' which is well known as 'commonjs' module which is introduced by Nodejs usually. The 'fs' is one of the internal module of Nodejs as well.
So if you still consist using client script to get the job done, you have to rewrite the script, not 'require' the 'fs' module. And use the file reader to get the content of a file object, which is generated by a file input usually.
A detailed introduction about how to read local files.
I write a HTA File with javascript to display some userinformation.
How can I run windows cmd commands (like in a batch file) and get the output in a variable.
What I need in Javascript syntax
batch-file code
net user %username% /domain | findstr /c:"password expires"
so that I have this in a variable in javascript function.
Same like this:
function username()
{
var wshshell=new ActiveXObject("wscript.shell");
var username=wshshell.ExpandEnvironmentStrings("%username%");
return username
}
function ipAddress() {
var ipAddress = "";
var wmi = GetObject("winmgmts:{impersonationLevel=impersonate}");
e = new Enumerator(wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True"));
for(; !e.atEnd(); e.moveNext()) {
var s = e.item();
ipAddress = s.IPAddress(0);
}
return ipAddress
}
You can use WScript.shell object. It allows you to execute shell commands.
var objShell = new ActiveXObject("WScript.shell");
It has run method.
https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/bb776890(v=vs.85)
I am creating an extension for simple git commands, and when a user enters a command in the Command Palette, like Init, I want to call git init on their current directory.
Unfortunately, there is no documentation on executing code locally with the VSCode extensions API. Is there any way to do this?
Yes, this is possible, by using child_process.spawn. I have used it in my extension to run a Java jar. The core of the execution is shown here:
let spawnOptions = { cwd: options.baseDir ? options.baseDir : undefined };
let java = child_process.spawn("java", parameters, spawnOptions);
let buffer = "";
java.stderr.on("data", (data) => {
let text = data.toString();
if (text.startsWith("Picked up _JAVA_OPTIONS:")) {
let endOfInfo = text.indexOf("\n");
if (endOfInfo == -1) {
text = "";
} else {
text = text.substr(endOfInfo + 1, text.length);
}
}
if (text.length > 0) {
buffer += "\n" + text;
}
});
java.on("close", (code) => {
// Handle the result + errors (i.e. the text in "buffer") here.
}
I am looking for a way of getting the process memory of any process running.
I am doing a web application. I have a server (through Nodejs), my file app.js, and an agent sending information to app.js through the server.
I would like to find a way to get the process memory of any process (in order to then sending this information to the agent) ?
Do you have any idea how I can do this ? I have searched on google but I haven't found my answer :/
Thank you
PS : I need a windows compatible solution :)
Windows
For windows, use tasklist instead of ps
In the example below, i use the ps unix program, so it's not windows compatible.
Here, the %MEM is the 4st element of each finalProcess iterations.
On Windows the %MEM is the 5th element.
var myFunction = function(processList) {
// here, your code
};
var parseProcess = function(err, process, stderr) {
var process = (process.split("\n")),
finalProcess = [];
// 1st line is a tab descriptor
// if Windows, i should start to 2
for (var i = 1; i < process.length; i++) {
finalProcess.push(cleanArray(process[i].split(" ")));
}
console.log(finalProcess);
// callback to another function
myFunction(finalProcess);
};
var getProcessList = function() {
var exec = require('child_process').exec;
exec('ps aux', parseProcess.bind(this));
}
// thx http://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript
function cleanArray(actual){
var newArray = new Array();
for(var i = 0; i<actual.length; i++){
if (actual[i]){
newArray.push(actual[i]);
}
}
return newArray;
}
getProcessList();