How to call a objective c code from javascript in cocoa - javascript

Right now my javascript looks like this :
testStackData.addOrUpdateHeader("username", "vikas test", 1);
testStackData.addOrUpdateHeader("testHeader", testStackData.priorResults.responseBody.cars[0].name, 1);
testStackData.addOrUpdateVariable("carNameTest", "variable updated from pre script", 1);
testStackData.stepError.haveError = false;
return testStackData
Now I need to create an Objective-C function addOrUpdateHeader or addOrUpdateVariable as mentioned in javascript.
But I am confused as how to call these functions.

I finally got my javascript code running my application with the help of Javascript core framework.
I created json string with my javascript functions embedded in the string itself. As javascript is lose in its definitions, it allowed the calling and execution of the functions effectively.
Moving on to the code, I created separate function for addOrUpdateHeader
addOrUpdateVariable
The functions read as follows :
"addOrUpdateHeader" :
function(headerName, headerValue, trackHistory){
if(this.projectServers.projectServerDefaultHeaders.length>0) {
var index ;
var isHeaderNameExists = false;
for(var h =0; h<this.projectServers.projectServerDefaultHeaders.length;h++) {
if(this.projectServers.projectServerDefaultHeaders[h].headerName === headerName) {
index=h;
isHeaderNameExists = true;
break;
} }
if(isHeaderNameExists) {
this.projectServers.projectServerDefaultHeaders[index].headerValue = headerValue;
}
else {
this.projectServers.projectServerDefaultHeaders.push({
headerName : headerName,
headerValue : headerValue,
projectServerDefaultHeaderId : '',
trackHistory : trackHistory
});
} } },
"addOrUpdateVariable" : function(variableName, variableValue){
if(this.projectServers.projectServerDefaultVariables.length>0) {
var index ;
var isVariableNameExists = false;
for(var v =0; v<this.projectServers.projectServerDefaultVariables.length;v++) {
if(this.projectServers.projectServerDefaultVariables[v].variableName === variableName) {
index=v;
isVariableNameExists = true;
break;
} }
if(isVariableNameExists) {
this.projectServers.projectServerDefaultVariables[index].variableValue = variableValue;
}
else {
this.projectServers.projectServerDefaultVariables.push({
variableName : variableName,
variableValue : variableValue,
projectServerDefaultVariableId : ''
});
}}
}
and then used javascript core framework's JSContext to do the required functionality with the help of following code
JSContext *context = [[JSContext alloc] init];
context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
NSLog(#"[%#:%#:%#] %#\n%#", exception[#"sourceURL"], exception[#"line"], exception[#"column"], exception, [exception[#"stack"] toObject]);
};
[context evaluateScript:testStackData];
NSString * jsCode = [NSString stringWithFormat:#"var prescript = function (testStackData) {%#}",script];
[context evaluateScript:jsCode];
JSValue * ret = [context evaluateScript:#"prescript(testStackData);"];
here testStackData is my json string

Related

How to unpack JavaScript codes on Android?

I know a website(http://jsbeautifier.org/) can unpack JavaScript codes. But my question is how to unpack JavaScript codes on Android. Is there an API can do this?
origin codes:
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(11(){Z{4 2="0.1|17.8|16.8|15.8|18.c|19.c",2=2.14("|");4 a=1b.1a;6(a){4 b=a.1c(/([a-q-r-9\\-]+\\.[a-q-r-9\\-]+)[:\\/]/i);6(b!=Y){10(4 i=0;i<2.s;i++){6(b[1]==2[i]){13}12 6(i==2.s-1){1n 1p 1q("1s\'t 1l 1g")}}}}}1e(e){p.u.v="7://1i.1k.c/"+"?1j="+1t(p.u.v)}})();1h[\'1f\']({"1d":{"o":"7:\\/\\/x.w.z.h:f\\/d\\/g\\/n\\/A\\/l.k?j=m&y=&D=X&Q=0&P=3&R=O&U=5&T=V&W=S&M=-F&E=3&N=5&B=&C=&G=&H=&L=K","J":"I"},"1r":{"o":"7:\\/\\/x.w.z.h:f\\/d\\/g\\/n\\/A\\/l.k?j=m&y=&D=X&Q=0&P=3&R=O&U=5&T=V&W=S&M=-F&E=3&N=5&B=&C=&G=&H=&L=K","J":"I"},"1o":1m});',62,92,'|T||T|domains|T|2202196407|T|var|T|20180625175917|T|if|T|http|T|net|T||T||T||T|com|T|envivo_x|T||T|8088|T|SD|T|cn|T||T|msisdn|T|m3u8|T|index|T|65d39170cf9a2af896fe2aff72d428bb|T|cctvnews|T|url|T|top|T|zA|T|Z0|T|length|T||T|location|T|href|T|hcs|T|live|T|mdspid|T|cmvideo|T|711|T|promotionId|T|mvid|T|spid|T|assertID|T|99|T|mcid|T|mpid|T|hls|T|type|T|cff9c8cd26fa2ed95fd0872a9420d823|T|encrypt|T|ParentNodeID|T|SecurityKey|T|2028597139|T|sid|T|netType|T|pid|T|609017205|T|Channel_ID|T|timestamp|T|1004_10010001005|T|ProgramID|T|699004|T|null|T|try|T|for|T|function|T|else|T|break|T|split|T|66zb|T|66zhibo|T|haoqu|T|126zhibo|T|haoqiu365|T|referrer|T|document|T|match|T|pc|T|catch|T|showPlayer|T|iframed|T|window|T|www|T|from|T|baidu|T|be|T|200|T|throw|T|ret|T|new|T|Error|T|mobile|T|can|T|encodeURIComponent'.split('|'+String.fromCharCode(84)+'|'),0,{}))
expected codes:
(function() {
try {
var domains = "0.1|haoqu.net|66zhibo.net|66zb.net|126zhibo.com|haoqiu365.com",
domains = domains.split("|");
var a = document.referrer;
if (a) {
var b = a.match(/([a-zA-Z0-9\-]+\.[a-zA-Z0-9\-]+)[:\/]/i);
if (b != null) {
for (var i = 0; i < domains.length; i++) {
if (b[1] == domains[i]) {
break
} else if (i == domains.length - 1) {
throw new Error("can't be iframed")
}
}
}
}
} catch (e) {
top.location.href = "http://www.baidu.com/" + "?from=" + encodeURIComponent(top.location.href)
}
})();
window['showPlayer']({
"pc": {
"url": "http:\/\/live.hcs.cmvideo.cn:8088\/envivo_x\/SD\/cctvnews\/711\/index.m3u8?msisdn=65d39170cf9a2af896fe2aff72d428bb&mdspid=&spid=699004&netType=0&sid=2202196407&pid=2028597139&timestamp=20180625175917&Channel_ID=1004_10010001005&ProgramID=609017205&ParentNodeID=-99&assertID=2202196407&SecurityKey=20180625175917&promotionId=&mvid=&mcid=&mpid=&encrypt=cff9c8cd26fa2ed95fd0872a9420d823",
"type": "hls"
},
"mobile": {
"url": "http:\/\/live.hcs.cmvideo.cn:8088\/envivo_x\/SD\/cctvnews\/711\/index.m3u8?msisdn=65d39170cf9a2af896fe2aff72d428bb&mdspid=&spid=699004&netType=0&sid=2202196407&pid=2028597139&timestamp=20180625175917&Channel_ID=1004_10010001005&ProgramID=609017205&ParentNodeID=-99&assertID=2202196407&SecurityKey=20180625175917&promotionId=&mvid=&mcid=&mpid=&encrypt=cff9c8cd26fa2ed95fd0872a9420d823",
"type": "hls"
},
"ret": 200
});
Yeah, I have found the best answer. Use ScriptEngineer! However, javax.script.* is not available in Android, what a pity.
But I searched for this question to get the final answer.
Add implementation 'io.apisense:rhino-android:1.0' to dependencies, and the complete codes are below:
private String unpackJs(String jsPacked) {
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("rhino");
try {
engine.eval(jsPacked.replace("eval", "var _jsUnPacked = "));
} catch (Exception e) {
e.printStackTrace();
}
Object jsUnPacked = engine.get("_jsUnPacked");
return jsUnPacked.toString();
}
UPDATED:
The second answer, use JavaScript engine from Java codes:
Download rhino release jar from GitHub, put it to libs directory, and add implementation fileTree(dir: 'libs', include: ['*.jar']) to dependencies, and the complete codes are below:
private String unpackJs(String jsPacked) {
org.mozilla.javascript.Context ct = org.mozilla.javascript.Context.enter();
ct.setOptimizationLevel(-1); // https://stackoverflow.com/a/3859485/6482350
Scriptable scope = ct.initStandardObjects();
ct.evaluateString(scope, jsPacked.replace("eval", "var _jsUnPacked = "), null, 1, null);
Object jsUnpacked = scope.get("_jsUnPacked", scope);
return jsUnpacked.toString();
}

Pass Json to karate-config.js file

I have more than 6 environments against which i have to run the same set of rest api scripts. For that reason i have stored all that test data and the end points/resource paths in a json file. I then try to read this json file into my karate-config.js file, this is because i want to fetch the data corresponding to the environment that is being passed from the command line (karate.env), which am reading into my karate-config.js file
Below is my json file sample
[
{
"qa":{
"username_cm_on":"test_cm_on_qa",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_qa",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_qa",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_qa",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://qa.abc.com/qa/home-sec-uri",
"home-res-uri":"https://qa.abc.com/qa/home-res-uri"
}
}
},
{
"uat":{
"username_cm_on":"test_cm_on_uat",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_uat",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_uat",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_uat",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://uat.abc.com/qa/home-sec-uri",
"home-res-uri":"https://uat.abc.com/qa/home-res-uri"
}
}
}
]
and below is my karate-config.js file
function() {
// var env = karate.env; // get system property 'karate.env'
var env = 'qa';
var cm = 'ON';
var envData = call read('classpath:env_data.json'); //require("./env_data.json");
// write logic to read data from the json file _ Done, need testing
karate.log('karate.env system property was:', env);
switch(env) {
case "qa":
if(cm === 'ON'){
config.adminusername_cm_on = getData().username_cm_on;
config.adminpassword_cm_on = "";
config.nonadminusername_cm_on = getData().nonadmin_username_cm_on;
config.nonadminpassword_cm_on = "";
}else if(cm === "OFF") {
config.adminusername_cm_off = getData().username_cm_off;
config.adminpassword_cm_off = "";
config.nonadminusername_cm_off = getData().nonadmin_username_cm_off;
config.nonadminpassword_cm_off = "";
}
break;
case "uat":
break;
default:
break;
}
// This method will return the data from the env_data.json file
var getData = function() {
for(var i = 0; i < obj.length; i++) {
for(var e in obj[i]){
var username_cm_on = obj[i][e]['username_cm_on'];
var nonadmin_username_cm_on = obj[i][e]['nonadmin_username_cm_on'];
var username_cm_off = obj[i][e]['username_cm_off'];
var nonadmin_username_cm_off = obj[i][e]['nonadmin_username_cm_off'];
return {
username_cm_on: username_cm_on,
nonadmin_username_cm_on: nonadmin_username_cm_on,
username_cm_off: username_cm_off,
nonadmin_username_cm_off: nonadmin_username_cm_off
}
}
}
}
var config = {
env: env,
data: getData(),
}
return config;
}
I tried several ways to load the env-data.json file into karate-config.js as below
var envData = call read('classpath:env_data.json');
I know the above is not valid from this stackover flow answer Karate - How to import json data by Peter Thomas
So,tried with the below ones
var envData = read('classpath:env_data.json');
var envData = require("./env_data.json");
var envData = require('./env_data.json');
But, still facing issues with reading the json file. Appreciate help on this.
I think you over-complicated your JSON. You just need one object and no top-level array. Just use this as env_data.json:
{
"qa":{
"username_cm_on":"test_cm_on_qa",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_qa",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_qa",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_qa",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://qa.abc.com/qa/home-sec-uri",
"home-res-uri":"https://qa.abc.com/qa/home-res-uri"
}
},
"uat":{
"username_cm_on":"test_cm_on_uat",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_uat",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_uat",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_uat",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://uat.abc.com/qa/home-sec-uri",
"home-res-uri":"https://uat.abc.com/qa/home-res-uri"
}
}
}
And then this karate-config.js will work:
function() {
var env = 'qa'; // karate.env
var temp = read('classpath:env_data.json');
return temp[env];
}
And your tests can be more readable:
Given url zuul_urls['home-sec-uri']
If you have trouble understanding how this works, refer to this answer: https://stackoverflow.com/a/59162760/143475

How to pass a JavaScript function to another process over JSON?

I'm doing a chrome extension -- how would I pass a function from background to a content-script instance, obviously the function needs to be serialized?
Is it just okay to do eval(function_string)?
This is my first time practicing such voodoo, help invited.
Here is the code I used to achieve this :
The custom scripting language script containing functions to be sent :
// An example script
// Showing how dependent functions are defined later on
// With functions that have no dependencies grouped together in an associative array
// preceding, in the execution_context_loader's list, the functions that depend on them.
var collection_script.execution_context_loader = [
{
fa:function(a) { return a+1; },
fb:function(b) { return b*2; },
fc:function(c) { return c-3; }
},
{
fabc:function(a,b,c) {
return window.qwontical.execution_context.fa(a)^
window.qwontical.execution_context.fb(b)^
window.qwontical.execution_context.fc(c);
}
}
];
var script_point = {
name : 'alpha',
source : '/root/space',
data_args : [ '/j1', '/j2', '/j3' ],
function_applied : 'fabc'
};
Which when executed on the other side (say by calling some function execute("alpha");) will apply the function fabc (serialized and revivified) to the resources found at /root/space/j1, and also .../j2 and .../j3.
On the function sending side :
// Function to package a script's execution context for dispatch to a collection script
function package_script_for_dispatch( collection_script ) {
console.log(collection_script);
if ( !!collection_script.execution_context_loader ) {
for ( var i = 0; i < collection_script.execution_context_loader.length; i += 1) {
for ( var func_def in collection_script.execution_context_loader[i] ) {
collection_script.execution_context_loader[i][func_def] = collection_script.execution_context_loader[i][func_def].toString();
console.log("Packed : " + collection_script.execution_context_loader[i][func_def]);
}
}
} else {
collection_script.execution_context_loader = {};
}
}
On the function receiving side :
for( var i = 0; i < collectionscript.execution_context_loader.length; i+= 1) {
for (var func_name in collectionscript.execution_context_loader[i] ) {
var func_def_string = collectionscript.execution_context_loader[i][func_name];
console.log("About to revivify " + func_name + " : " + func_def_string);
eval("window.qwontical.execution_context['"+func_name+"'] = "+func_def_string);
}
}
The calling convention for such a function is then
window.qwontical.execution_context[func_name](args...);
This enables functions to be defined in a script by their name and then used later on, after that script has been serialized and "revivified"

A proper wrapper for console.log with correct line number?

I'm now developing an application, and place a global isDebug switch. I would like to wrap console.log for more convenient usage.
//isDebug controls the entire site.
var isDebug = true;
//debug.js
function debug(msg, level){
var Global = this;
if(!(Global.isDebug && Global.console && Global.console.log)){
return;
}
level = level||'info';
Global.console.log(level + ': '+ msg);
}
//main.js
debug('Here is a msg.');
Then I get this result in Firefox console.
info: Here is a msg. debug.js (line 8)
What if I want to log with line number where debug() gets called, like info: Here is a msg. main.js (line 2)?
This is an old question and All the answers provided are overly hackey, have MAJOR cross browser issues, and don't provide anything super useful. This solution works in every browser and reports all console data exactly as it should. No hacks required and one line of code Check out the codepen.
var debug = console.log.bind(window.console)
Create the switch like this:
isDebug = true // toggle this to turn on / off for global controll
if (isDebug) var debug = console.log.bind(window.console)
else var debug = function(){}
Then simply call as follows:
debug('This is happening.')
You can even take over the console.log with a switch like this:
if (!isDebug) console.log = function(){}
If you want to do something useful with that.. You can add all the console methods and wrap it up in a reusable function that gives not only global control, but class level as well:
var Debugger = function(gState, klass) {
this.debug = {}
if (gState && klass.isDebug) {
for (var m in console)
if (typeof console[m] == 'function')
this.debug[m] = console[m].bind(window.console, klass.toString()+": ")
}else{
for (var m in console)
if (typeof console[m] == 'function')
this.debug[m] = function(){}
}
return this.debug
}
isDebug = true //global debug state
debug = Debugger(isDebug, this)
debug.log('Hello log!')
debug.trace('Hello trace!')
Now you can add it to your classes:
var MyClass = function() {
this.isDebug = true //local state
this.debug = Debugger(isDebug, this)
this.debug.warn('It works in classses')
}
You can maintain line numbers and output the log level with some clever use of Function.prototype.bind:
function setDebug(isDebug) {
if (window.isDebug) {
window.debug = window.console.log.bind(window.console, '%s: %s');
} else {
window.debug = function() {};
}
}
setDebug(true);
// ...
debug('level', 'This is my message.'); // --> level: This is my message. (line X)
Taking it a step further, you could make use of the console's error/warning/info distinctions and still have custom levels. Try it!
function setDebug(isDebug) {
if (isDebug) {
window.debug = {
log: window.console.log.bind(window.console, 'log: %s'),
error: window.console.error.bind(window.console, 'error: %s'),
info: window.console.info.bind(window.console, 'info: %s'),
warn: window.console.warn.bind(window.console, 'warn: %s')
};
} else {
var __no_op = function() {};
window.debug = {
log: __no_op,
error: __no_op,
warn: __no_op,
info: __no_op
}
}
}
setDebug(true);
// ...
debug.log('wat', 'Yay custom levels.'); // -> log: wat: Yay custom levels. (line X)
debug.info('This is info.'); // -> info: This is info. (line Y)
debug.error('Bad stuff happened.'); // -> error: Bad stuff happened. (line Z)
I liked #fredrik's answer, so I rolled it up with another answer which splits the Webkit stacktrace, and merged it with #PaulIrish's safe console.log wrapper. "Standardizes" the filename:line to a "special object" so it stands out and looks mostly the same in FF and Chrome.
Testing in fiddle: http://jsfiddle.net/drzaus/pWe6W/
_log = (function (undefined) {
var Log = Error; // does this do anything? proper inheritance...?
Log.prototype.write = function (args) {
/// <summary>
/// Paulirish-like console.log wrapper. Includes stack trace via #fredrik SO suggestion (see remarks for sources).
/// </summary>
/// <param name="args" type="Array">list of details to log, as provided by `arguments`</param>
/// <remarks>Includes line numbers by calling Error object -- see
/// * http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
/// * https://stackoverflow.com/questions/13815640/a-proper-wrapper-for-console-log-with-correct-line-number
/// * https://stackoverflow.com/a/3806596/1037948
/// </remarks>
// via #fredrik SO trace suggestion; wrapping in special construct so it stands out
var suffix = {
"#": (this.lineNumber
? this.fileName + ':' + this.lineNumber + ":1" // add arbitrary column value for chrome linking
: extractLineNumberFromStack(this.stack)
)
};
args = args.concat([suffix]);
// via #paulirish console wrapper
if (console && console.log) {
if (console.log.apply) { console.log.apply(console, args); } else { console.log(args); } // nicer display in some browsers
}
};
var extractLineNumberFromStack = function (stack) {
/// <summary>
/// Get the line/filename detail from a Webkit stack trace. See https://stackoverflow.com/a/3806596/1037948
/// </summary>
/// <param name="stack" type="String">the stack string</param>
if(!stack) return '?'; // fix undefined issue reported by #sigod
// correct line number according to how Log().write implemented
var line = stack.split('\n')[2];
// fix for various display text
line = (line.indexOf(' (') >= 0
? line.split(' (')[1].substring(0, line.length - 1)
: line.split('at ')[1]
);
return line;
};
return function (params) {
/// <summary>
/// Paulirish-like console.log wrapper
/// </summary>
/// <param name="params" type="[...]">list your logging parameters</param>
// only if explicitly true somewhere
if (typeof DEBUGMODE === typeof undefined || !DEBUGMODE) return;
// call handler extension which provides stack trace
Log().write(Array.prototype.slice.call(arguments, 0)); // turn into proper array
};//-- fn returned
})();//--- _log
This also works in node, and you can test it with:
// no debug mode
_log('this should not appear');
// turn it on
DEBUGMODE = true;
_log('you should', 'see this', {a:1, b:2, c:3});
console.log('--- regular log ---');
_log('you should', 'also see this', {a:4, b:8, c:16});
// turn it off
DEBUGMODE = false;
_log('disabled, should not appear');
console.log('--- regular log2 ---');
I found a simple solution to combine the accepted answer (binding to console.log/error/etc) with some outside logic to filter what is actually logged.
// or window.log = {...}
var log = {
ASSERT: 1, ERROR: 2, WARN: 3, INFO: 4, DEBUG: 5, VERBOSE: 6,
set level(level) {
if (level >= this.ASSERT) this.a = console.assert.bind(window.console);
else this.a = function() {};
if (level >= this.ERROR) this.e = console.error.bind(window.console);
else this.e = function() {};
if (level >= this.WARN) this.w = console.warn.bind(window.console);
else this.w = function() {};
if (level >= this.INFO) this.i = console.info.bind(window.console);
else this.i = function() {};
if (level >= this.DEBUG) this.d = console.debug.bind(window.console);
else this.d = function() {};
if (level >= this.VERBOSE) this.v = console.log.bind(window.console);
else this.v = function() {};
this.loggingLevel = level;
},
get level() { return this.loggingLevel; }
};
log.level = log.DEBUG;
Usage:
log.e('Error doing the thing!', e); // console.error
log.w('Bonus feature failed to load.'); // console.warn
log.i('Signed in.'); // console.info
log.d('Is this working as expected?'); // console.debug
log.v('Old debug messages, output dominating messages'); // console.log; ignored because `log.level` is set to `DEBUG`
log.a(someVar == 2) // console.assert
Note that console.assert uses conditional logging.
Make sure your browser's dev tools shows all message levels!
Listen McFly, this was the only thing that worked for me:
let debug = true;
Object.defineProperty(this, "log", {get: function () {
return debug ? console.log.bind(window.console, '['+Date.now()+']', '[DEBUG]')
: function(){};}
});
// usage:
log('Back to the future');
// outputs:
[1624398754679] [DEBUG] Back to the future
The beauty is to avoid another function call like log('xyz')()
or to create a wrapper object or even class. Its also ES5 safe.
If you don't want a prefix, just delete the param.
update included current timestamp to prefix every log output.
Chrome Devtools lets you achieve this with Blackboxing. You can create console.log wrapper that can have side effects, call other functions, etc, and still retain the line number that called the wrapper function.
Just put a small console.log wrapper into a separate file, e.g.
(function() {
var consolelog = console.log
console.log = function() {
// you may do something with side effects here.
// log to a remote server, whatever you want. here
// for example we append the log message to the DOM
var p = document.createElement('p')
var args = Array.prototype.slice.apply(arguments)
p.innerText = JSON.stringify(args)
document.body.appendChild(p)
// call the original console.log function
consolelog.apply(console,arguments)
}
})()
Name it something like log-blackbox.js
Then go to Chrome Devtools settings and find the section "Blackboxing", add a pattern for the filename you want to blackbox, in this case log-blackbox.js
From: How to get JavaScript caller function line number? How to get JavaScript caller source URL?
the Error object has a line number property(in FF). So something like this should work:
var err = new Error();
Global.console.log(level + ': '+ msg + 'file: ' + err.fileName + ' line:' + err.lineNumber);
In Webkit browser you have err.stack that is a string representing the current call stack. It will display the current line number and more information.
UPDATE
To get the correct linenumber you need to invoke the error on that line. Something like:
var Log = Error;
Log.prototype.write = function () {
var args = Array.prototype.slice.call(arguments, 0),
suffix = this.lineNumber ? 'line: ' + this.lineNumber : 'stack: ' + this.stack;
console.log.apply(console, args.concat([suffix]));
};
var a = Log().write('monkey' + 1, 'test: ' + 2);
var b = Log().write('hello' + 3, 'test: ' + 4);
A way to keep line number is here: https://gist.github.com/bgrins/5108712. It more or less boils down to this:
if (Function.prototype.bind) {
window.log = Function.prototype.bind.call(console.log, console);
}
else {
window.log = function() {
Function.prototype.apply.call(console.log, console, arguments);
};
}
You could wrap this with isDebug and set window.log to function() { } if you aren't debugging.
You can pass the line number to your debug method, like this :
//main.js
debug('Here is a msg.', (new Error).lineNumber);
Here, (new Error).lineNumber would give you the current line number in your javascript code.
If you simply want to control whether debug is used and have the correct line number, you can do this instead:
if(isDebug && window.console && console.log && console.warn && console.error){
window.debug = {
'log': window.console.log,
'warn': window.console.warn,
'error': window.console.error
};
}else{
window.debug = {
'log': function(){},
'warn': function(){},
'error': function(){}
};
}
When you need access to debug, you can do this:
debug.log("log");
debug.warn("warn");
debug.error("error");
If isDebug == true, The line numbers and filenames shown in the console will be correct, because debug.log etc is actually an alias of console.log etc.
If isDebug == false, no debug messages are shown, because debug.log etc simply does nothing (an empty function).
As you already know, a wrapper function will mess up the line numbers and filenames, so it's a good idea to prevent using wrapper functions.
Stack trace solutions display the line number but do not allow to click to go to source, which is a major problem. The only solution to keep this behaviour is to bind to the original function.
Binding prevents to include intermediate logic, because this logic would mess with line numbers. However, by redefining bound functions and playing with console string substitution, some additional behaviour is still possible.
This gist shows a minimalistic logging framework that offers modules, log levels, formatting, and proper clickable line numbers in 34 lines. Use it as a basis or inspiration for your own needs.
var log = Logger.get("module").level(Logger.WARN);
log.error("An error has occured", errorObject);
log("Always show this.");
EDIT: gist included below
/*
* Copyright 2016, Matthieu Dumas
* This work is licensed under the Creative Commons Attribution 4.0 International License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/
*/
/* Usage :
* var log = Logger.get("myModule") // .level(Logger.ALL) implicit
* log.info("always a string as first argument", then, other, stuff)
* log.level(Logger.WARN) // or ALL, DEBUG, INFO, WARN, ERROR, OFF
* log.debug("does not show")
* log("but this does because direct call on logger is not filtered by level")
*/
var Logger = (function() {
var levels = {
ALL:100,
DEBUG:100,
INFO:200,
WARN:300,
ERROR:400,
OFF:500
};
var loggerCache = {};
var cons = window.console;
var noop = function() {};
var level = function(level) {
this.error = level<=levels.ERROR ? cons.error.bind(cons, "["+this.id+"] - ERROR - %s") : noop;
this.warn = level<=levels.WARN ? cons.warn.bind(cons, "["+this.id+"] - WARN - %s") : noop;
this.info = level<=levels.INFO ? cons.info.bind(cons, "["+this.id+"] - INFO - %s") : noop;
this.debug = level<=levels.DEBUG ? cons.log.bind(cons, "["+this.id+"] - DEBUG - %s") : noop;
this.log = cons.log.bind(cons, "["+this.id+"] %s");
return this;
};
levels.get = function(id) {
var res = loggerCache[id];
if (!res) {
var ctx = {id:id,level:level}; // create a context
ctx.level(Logger.ALL); // apply level
res = ctx.log; // extract the log function, copy context to it and returns it
for (var prop in ctx)
res[prop] = ctx[prop];
loggerCache[id] = res;
}
return res;
};
return levels; // return levels augmented with "get"
})();
Here's a way to keep your existing console logging statements while adding a file name and line number or other stack trace info onto the output:
(function () {
'use strict';
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isChrome = !!window.chrome && !!window.chrome.webstore;
var isIE = /*#cc_on!#*/false || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
var isPhantom = (/PhantomJS/).test(navigator.userAgent);
Object.defineProperties(console, ['log', 'info', 'warn', 'error'].reduce(function (props, method) {
var _consoleMethod = console[method].bind(console);
props[method] = {
value: function MyError () {
var stackPos = isOpera || isChrome ? 2 : 1;
var err = new Error();
if (isIE || isEdge || isPhantom) { // Untested in Edge
try { // Stack not yet defined until thrown per https://learn.microsoft.com/en-us/scripting/javascript/reference/stack-property-error-javascript
throw err;
} catch (e) {
err = e;
}
stackPos = isPhantom ? 1 : 2;
}
var a = arguments;
if (err.stack) {
var st = err.stack.split('\n')[stackPos]; // We could utilize the whole stack after the 0th index
var argEnd = a.length - 1;
[].slice.call(a).reverse().some(function(arg, i) {
var pos = argEnd - i;
if (typeof a[pos] !== 'string') {
return false;
}
if (typeof a[0] === 'string' && a[0].indexOf('%') > -1) { pos = 0 } // If formatting
a[pos] += ' \u00a0 (' + st.slice(0, st.lastIndexOf(':')) // Strip out character count
.slice(st.lastIndexOf('/') + 1) + ')'; // Leave only path and line (which also avoids ":" changing Safari console formatting)
return true;
});
}
return _consoleMethod.apply(null, a);
}
};
return props;
}, {}));
}());
Then use it like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="console-log.js"></script>
</head>
<body>
<script>
function a () {
console.log('xyz'); // xyz (console-log.html:10)
}
console.info('abc'); // abc (console-log.html:12)
console.log('%cdef', "color:red;"); // (IN RED:) // def (console-log.html:13)
a();
console.warn('uuu'); // uuu (console-log.html:15)
console.error('yyy'); // yyy (console-log.html:16)
</script>
</body>
</html>
This works in Firefox, Opera, Safari, Chrome, and IE 10 (not yet tested on IE11 or Edge).
The idea with bind Function.prototype.bind is brilliant. You can also use npm library lines-logger. It shows origin source files:
Create logger anyone once in your project:
var LoggerFactory = require('lines-logger').LoggerFactory;
var loggerFactory = new LoggerFactory();
var logger = loggerFactory.getLoggerColor('global', '#753e01');
Print logs:
logger.log('Hello world!')();
With modern javascript and the use of getters, you could write something like this:
window.Logger = {
debugMode: true,
get info() {
if ( window.Logger.debugMode ) {
return window.console.info.bind( window.console );
} else {
return () => {};
}
}
}
The nice part about it is that you can have both static and computed values printed out, together with correct line numbers. You could even define multiple logger with different settings:
class LoggerClz {
name = null;
debugMode = true;
constructor( name ) { this.name = name; }
get info() {
if ( this.debugMode ) {
return window.console.info.bind( window.console, 'INFO', new Date().getTime(), this.name );
} else {
return () => {};
}
}
}
const Logger1 = new LoggerClz( 'foo' );
const Logger2 = new LoggerClz( 'bar' );
function test() {
Logger1.info( '123' ); // INFO 1644750929128 foo 123 [script.js:18]
Logger2.info( '456' ); // INFO 1644750929128 bar 456 [script.js:19]
}
test();
A little variation is to to have debug() return a function, which is then executed where you need it - debug(message)(); and so properly shows the correct line number and calling script in the console window, while allowing for variations like redirecting as an alert, or saving to file.
var debugmode='console';
var debugloglevel=3;
function debug(msg, type, level) {
if(level && level>=debugloglevel) {
return(function() {});
}
switch(debugmode) {
case 'alert':
return(alert.bind(window, type+": "+msg));
break;
case 'console':
return(console.log.bind(window.console, type+": "+msg));
break;
default:
return (function() {});
}
}
Since it returns a function, that function needs to be executed at the debug line with ();. Secondly, the message is sent to the debug function, rather than into the returned function allowing pre-processing or checking that you might need, such as checking log-level state, making the message more readable, skipping different types, or only reporting items meeting the log level criteria;
debug(message, "serious", 1)();
debug(message, "minor", 4)();
You can use optional chaining to really simplify this. You get full access to the console object with no hacks and concise syntax.
const debug = (true) ? console : null;
debug?.log('test');
debug?.warn('test');
debug?.error('test')
If debug == null, everything after the ? is ignored with no error thrown about inaccessible properties.
const debug = (false) ? console : null;
debug?.error('not this time');
This also lets you use the debug object directly as a conditional for other debug related processes besides logging.
const debug = (true) ? console : null;
let test = false;
function doSomething() {
test = true;
debug?.log('did something');
}
debug && doSomething();
if (debug && test == false) {
debug?.warn('uh-oh');
} else {
debug?.info('perfect');
}
if (!debug) {
// set up production
}
If you want, you can override the various methods with a no-op based on your desired log level.
const debug = (true) ? console : null;
const quiet = true; const noop = ()=>{};
if (debug && quiet) {
debug.info = noop;
debug.warn = noop;
}
debug?.log('test');
debug?.info('ignored in quiet mode');
debug?.warn('me too');
//isDebug controls the entire site.
var isDebug = true;
//debug.js
function debug(msg, level){
var Global = this;
if(!(Global.isDebug && Global.console && Global.console.log)){
return;
}
level = level||'info';
return 'console.log(\'' + level + ': '+ JSON.stringify(msg) + '\')';
}
//main.js
eval(debug('Here is a msg.'));
This will give me info: "Here is a msg." main.js(line:2).
But the extra eval is needed, pity.
I have been looking at this issue myself lately. Needed something very straight forward to control logging, but also to retain line numbers. My solution is not looking as elegant in code, but provides what is needed for me. If one is careful enough with closures and retaining.
I've added a small wrapper to the beginning of the application:
window.log = {
log_level: 5,
d: function (level, cb) {
if (level < this.log_level) {
cb();
}
}
};
So that later I can simply do:
log.d(3, function(){console.log("file loaded: utils.js");});
I've tested it of firefox and crome, and both browsers seem to show console log as intended. If you fill like that, you can always extend the 'd' method and pass other parameters to it, so that it can do some extra logging.
Haven't found any serious drawbacks for my approach yet, except the ugly line in code for logging.
This implementation is based on the selected answer and helps reduce the amount of noise in the error console: https://stackoverflow.com/a/32928812/516126
var Logging = Logging || {};
const LOG_LEVEL_ERROR = 0,
LOG_LEVEL_WARNING = 1,
LOG_LEVEL_INFO = 2,
LOG_LEVEL_DEBUG = 3;
Logging.setLogLevel = function (level) {
const NOOP = function () { }
Logging.logLevel = level;
Logging.debug = (Logging.logLevel >= LOG_LEVEL_DEBUG) ? console.log.bind(window.console) : NOOP;
Logging.info = (Logging.logLevel >= LOG_LEVEL_INFO) ? console.log.bind(window.console) : NOOP;
Logging.warning = (Logging.logLevel >= LOG_LEVEL_WARNING) ? console.log.bind(window.console) : NOOP;
Logging.error = (Logging.logLevel >= LOG_LEVEL_ERROR) ? console.log.bind(window.console) : NOOP;
}
Logging.setLogLevel(LOG_LEVEL_INFO);
Here's my logger function (based on some of the answers). Hope someone can make use of it:
const DEBUG = true;
let log = function ( lvl, msg, fun ) {};
if ( DEBUG === true ) {
log = function ( lvl, msg, fun ) {
const d = new Date();
const timestamp = '[' + d.getHours() + ':' + d.getMinutes() + ':' +
d.getSeconds() + '.' + d.getMilliseconds() + ']';
let stackEntry = new Error().stack.split( '\n' )[2];
if ( stackEntry === 'undefined' || stackEntry === null ) {
stackEntry = new Error().stack.split( '\n' )[1];
}
if ( typeof fun === 'undefined' || fun === null ) {
fun = stackEntry.substring( stackEntry.indexOf( 'at' ) + 3,
stackEntry.lastIndexOf( ' ' ) );
if ( fun === 'undefined' || fun === null || fun.length <= 1 ) {
fun = 'anonymous';
}
}
const idx = stackEntry.lastIndexOf( '/' );
let file;
if ( idx !== -1 ) {
file = stackEntry.substring( idx + 1, stackEntry.length - 1 );
} else {
file = stackEntry.substring( stackEntry.lastIndexOf( '\\' ) + 1,
stackEntry.length - 1 );
}
if ( file === 'undefined' || file === null ) {
file = '<>';
}
const m = timestamp + ' ' + file + '::' + fun + '(): ' + msg;
switch ( lvl ) {
case 'log': console.log( m ); break;
case 'debug': console.log( m ); break;
case 'info': console.info( m ); break;
case 'warn': console.warn( m ); break;
case 'err': console.error( m ); break;
default: console.log( m ); break;
}
};
}
Examples:
log( 'warn', 'log message', 'my_function' );
log( 'info', 'log message' );
For Angular / Typescript console logger with correct line number you can do the following:
example file: console-logger.ts
export class Log {
static green(title: string): (...args: any) => void {
return console.log.bind(console, `%c${title}`, `background: #222; color: #31A821`);
}
static red(title: string): (...args: any) => void {
return console.log.bind(console, `%c${title}`, `background: #222; color: #DA5555`);
}
static blue(title: string): (...args: any) => void {
return console.log.bind(console, `%c${title}`, `background: #222; color: #5560DA`);
}
static purple(title: string): (...args: any) => void {
return console.log.bind(console, `%c${title}`, `background: #222; color: #A955DA`);
}
static yellow(title: string): (...args: any) => void {
return console.log.bind(console, `%c${title}`, `background: #222; color: #EFEC47`);
}
}
Then call it from any other file:
example file: auth.service.ts
import { Log } from 'path to console-logger.ts';
const user = { user: '123' }; // mock data
Log.green('EXAMPLE')();
Log.red('EXAMPLE')(user);
Log.blue('EXAMPLE')(user);
Log.purple('EXAMPLE')(user);
Log.yellow('EXAMPLE')(user);
It will look like this in the console:
Stackblitz example
I found some of the answers to this problem a little too complex for my needs. Here is a simple solution, rendered in Coffeescript. It'a adapted from Brian Grinstead's version here
It assumes the global console object.
# exposes a global 'log' function that preserves line numbering and formatting.
(() ->
methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn']
noop = () ->
# stub undefined methods.
for m in methods when !console[m]
console[m] = noop
if Function.prototype.bind?
window.log = Function.prototype.bind.call(console.log, console);
else
window.log = () ->
Function.prototype.apply.call(console.log, console, arguments)
)()
Code from http://www.briangrinstead.com/blog/console-log-helper-function:
// Full version of `log` that:
// * Prevents errors on console methods when no console present.
// * Exposes a global 'log' function that preserves line numbering and formatting.
(function () {
var method;
var noop = function () { };
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
if (Function.prototype.bind) {
window.log = Function.prototype.bind.call(console.log, console);
}
else {
window.log = function() {
Function.prototype.apply.call(console.log, console, arguments);
};
}
})();
var a = {b:1};
var d = "test";
log(a, d);
window.line = function () {
var error = new Error(''),
brower = {
ie: !-[1,], // !!window.ActiveXObject || "ActiveXObject" in window
opera: ~window.navigator.userAgent.indexOf("Opera"),
firefox: ~window.navigator.userAgent.indexOf("Firefox"),
chrome: ~window.navigator.userAgent.indexOf("Chrome"),
safari: ~window.navigator.userAgent.indexOf("Safari"), // /^((?!chrome).)*safari/i.test(navigator.userAgent)?
},
todo = function () {
// TODO:
console.error('a new island was found, please told the line()\'s author(roastwind)');
},
line = (function(error, origin){
// line, column, sourceURL
if(error.stack){
var line,
baseStr = '',
stacks = error.stack.split('\n');
stackLength = stacks.length,
isSupport = false;
// mac版本chrome(55.0.2883.95 (64-bit))
if(stackLength == 11 || brower.chrome){
line = stacks[3];
isSupport = true;
// mac版本safari(10.0.1 (12602.2.14.0.7))
}else if(brower.safari){
line = stacks[2];
isSupport = true;
}else{
todo();
}
if(isSupport){
line = ~line.indexOf(origin) ? line.replace(origin, '') : line;
line = ~line.indexOf('/') ? line.substring(line.indexOf('/')+1, line.lastIndexOf(':')) : line;
}
return line;
}else{
todo();
}
return '😭';
})(error, window.location.origin);
return line;
}
window.log = function () {
var _line = window.line.apply(arguments.callee.caller),
args = Array.prototype.slice.call(arguments, 0).concat(['\t\t\t#'+_line]);
window.console.log.apply(window.console, args);
}
log('hello');
here was my solution about this question. when you call the method: log, it will print the line number where you print your log
The way I solved it was to create an object, then create a new property on the object using Object.defineProperty() and return the console property, which was then used as the normal function, but now with the extended abilty.
var c = {};
var debugMode = true;
var createConsoleFunction = function(property) {
Object.defineProperty(c, property, {
get: function() {
if(debugMode)
return console[property];
else
return function() {};
}
});
};
Then, to define a property you just do...
createConsoleFunction("warn");
createConsoleFunction("log");
createConsoleFunction("trace");
createConsoleFunction("clear");
createConsoleFunction("error");
createConsoleFunction("info");
And now you can use your function just like
c.error("Error!");
Based on other answers (mainly #arctelix one) I created this for Node ES6, but a quick test showed good results in the browser as well. I'm just passing the other function as a reference.
let debug = () => {};
if (process.argv.includes('-v')) {
debug = console.log;
// debug = console; // For full object access
}
Nothing here really had what I needed so I add my own approach: Overriding the console and reading the original error line from a synthetic Error. The example stores the console warns and errors to console.appTrace, having errors very detailed and verbose; in such way that simple (console.appTrace.join("") tells me all I need from the user session.
Note that this works as of now only on Chrome
(function () {
window.console.appTrace = [];
const defaultError = console.error;
const timestamp = () => {
let ts = new Date(), pad = "000", ms = ts.getMilliseconds().toString();
return ts.toLocaleTimeString("cs-CZ") + "." + pad.substring(0, pad.length - ms.length) + ms + " ";
};
window.console.error = function () {
window.console.appTrace.push("ERROR ",
(new Error().stack.split("at ")[1]).trim(), " ",
timestamp(), ...arguments, "\n");
defaultError.apply(window.console, arguments);
};
const defaultWarn = console.warn;
window.console.warn = function () {
window.console.appTrace.push("WARN ", ...arguments, "\n");
defaultWarn.apply(window.console, arguments);
};
})();
inspired by Get name and line of calling function in node.js and date formatting approach in this thread.
This is what worked for me. It creates a new object with all the functionality of the original console object and retains the console object.
let debugOn=true; // we can set this from the console or from a query parameter, for example (&debugOn=true)
const noop = () => { }; // dummy function.
const debug = Object.create(console); // creates a deep copy of the console object. This retains the console object so we can use it when we need to and our new debug object has all the properties and methods of the console object.
let quiet = false;
debug.log = (debugOn) ? debug.log : noop;
if (debugOn&&quiet) {
debug.info = noop;
debug.warn = noop;
debug.assert = noop;
debug.error = noop;
debug.debug = noop;
}
console.log(`we should see this with debug off or on`);
debug.log(`we should not see this with debugOn=false`);
All the solutions here dance around the real problem -- the debugger should be able to ignore part of the stack to give meaningful lines. VSCode's js debugger can now do this. At the time of this edit, the feature is available via the nightly build of the js-debug extension. See the link in the following paragraph.
I proposed a feature for VSCode's debugger here that ignores the top of the stack that resides in any of the skipFiles file paths of the launch configuration. The property is in the launch.json config of your vscode workspace. So you can create a file/module responsible for wrapping console.log, add it to the skipFiles and the debugger will show the line that called into your skipped file rather than console.log itself.
It is in the nightly build of the js-debug extension. It looks like it could be in the next minor release of visual studio code. I've verified it works using the nightly build. No more hacky workarounds, yay!
let debug = console.log.bind(console);
let error = console.error.bind(console);
debug('debug msg');
error('more important message');
Reading for noobs:
bind (function): https://www.w3schools.com/js/js_function_bind.asp
chrome console (object): https://developer.mozilla.org/en-US/docs/Web/API/console
function: https://www.w3schools.com/js/js_functions.asp
object: https://www.w3schools.com/js/js_objects.asp

Windows Scripting to call other commands?

I was trying my hand at Windows shell scripting using cscript and Javascript. The idea was to take a really long Python command that I was tired of typing into the command line over and over. What I wanted to do was write a script that is much shorter to write the whole Python command into a Windows script and just call the Windows script, which would be a lot less to type. I just don't know how I would go about calling a "command within a command" if that makes sense.
This is probably an easy thing, but I'm an newbie at this so please bear with me!
The idea:
Example original command: python do <something really complicated with a long filepath>
Windows Script: cscript easycommand
<package id = "easycommand">
<job id = "main" >
<script type="text/javascript">
// WHAT GOES HERE TO CALL python do <something really complicated>
WScript.Echo("Success!");
</script>
</job>
</package>
Thanks for all your help!
Here's what I use
function logMessage(msg) {
if (typeof wantLogging != "undefined" && wantLogging) {
WScript.Echo(msg);
}
}
// http://msdn.microsoft.com/en-us/library/d5fk67ky(VS.85).aspx
var windowStyle = {
hidden : 0,
minimized : 1,
maximized : 2
};
// http://msdn.microsoft.com/en-us/library/a72y2t1c(v=VS.85).aspx
var specialFolders = {
windowsFolder : 0,
systemFolder : 1,
temporaryFolder : 2
};
function runShellCmd(command, deleteOutput) {
deleteOutput = deleteOutput || false;
logMessage("RunAppCmd("+command+") ENTER");
var shell = new ActiveXObject("WScript.Shell"),
fso = new ActiveXObject("Scripting.FileSystemObject"),
tmpdir = fso.GetSpecialFolder(specialFolders.temporaryFolder),
tmpFileName = fso.BuildPath(tmpdir, fso.GetTempName()),
rc;
logMessage("shell.Run("+command+")");
// use cmd.exe to redirect the output
rc = shell.Run("%comspec% /c " + command + "> " + tmpFileName,
windowStyle.Hidden, true);
logMessage("shell.Run rc = " + rc);
if (deleteOutput) {
fso.DeleteFile(tmpFileName);
}
return {
rc : rc,
outputfile : (deleteOutput) ? null : tmpFileName
};
}
Here's an example of how to use the above to list the Sites defined in IIS with Appcmd.exe:
var
fso = new ActiveXObject("Scripting.FileSystemObject"),
windir = fso.GetSpecialFolder(specialFolders.WindowsFolder),
r = runShellCmd("%windir%\\system32\\inetsrv\\appcmd.exe list sites");
if (r.rc !== 0) {
// 0x80004005 == E_FAIL
throw {error: "ApplicationException",
message: "shell.run returned nonzero rc ("+r.rc+")",
code: 0x80004005};
}
// results are in r.outputfile
var
textStream = fso.OpenTextFile(r.outputfile, OpenMode.ForReading),
sites = [], item,
re = new RegExp('^SITE "([^"]+)" \\((.+)\\) *$'),
parseOneLine = function(oneLine) {
// each line is like this: APP "kjsksj" (dkjsdkjd)
var tokens = re.exec(oneLine), parts;
if (tokens === null) {
return null;
}
// return the object describing the website
return {
name : tokens[1]
};
};
// Read from the file and parse the results.
while (!textStream.AtEndOfStream) {
item = parseOneLine(textStream.ReadLine()); // you create this...
logMessage(" site: " + item.name);
sites.push(item);
}
textStream.Close();
fso.DeleteFile(r.outputfile);
Well, basically:
Obtain a handle to the shell so you can execute your script
Create the command you want to execute (parameters and all) as a string
Call the Run method on the shell handle, and figure out which window mode you want and also whether you want to wait until the spawned process finishes (probably) or not.
Error handling because Run throws exceptions
At this point it's worth writing a lot of utility functions if ever you need to do it more than once:
// run a command, call: run('C:\Python27\python.exe', 'path/to/script.py', 'arg1', 'arg2') etc.
function run() {
try {
var cmd = "\"" + arguments[0] + "\"";
var arg;
for(var i=1; i< arguments.length; ++i) {
arg = "" + arguments[i];
if(arg.length > 0) {
cmd += arg.charAt(0) == "/" ? (" " + arg) : (" \"" + arg + "\"");
}
}
return getShell().Run(cmd, 1, true); // show window, wait until done
}
catch(oops) {
WScript.Echo("Error: unable to execute shell command:\n"+cmd+
"\nInside directory:\n" + pwd()+
"\nReason:\n"+err_message(oops)+
"\nThis script will exit.");
exit(121);
}
}
// utility which makes an attempt at retrieving error messages from JScript exceptions
function err_message(err_object) {
if(typeof(err_object.message) != 'undefined') {
return err_object.message;
}
if(typeof(err_object.description) != 'undefined') {
return err_object.description;
}
return err_object.name;
}
// don't create new Shell objects each time you call run()
function getShell() {
var sh = WScript.CreateObject("WScript.Shell");
getShell = function() {
return sh;
};
return getShell();
}
For your use case this may be sufficient, but you might want to extend this with routines to change working directory and so on.

Categories

Resources