Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I wrote this little piece of code for viewing the profile pictures that are set as private. But every time I have to access it, I have to turn Apache on on XAMPP. Also, it is pretty much useless on a computer that doesn't have Apache installed. So I wanted to write it in JavaScript but couldn't find an equivalent for strstr() function.
Could someone please let me know if there's an equivalent or alternative?
The code:
<?php
//haystack
$_POST['theaddress'] ='160x160/photo.jpg';
//return all after the needle '160x160/', inclusive
$varA = strstr($_POST['theaddress'], '160x160/');
//build new URL
$varA = "https://fbcdn-sphotos-g-a.akamaihd.net/hphotos-ak-ash3/t1.0-9"."$varA";
header("Location: $varA");
?>
You can try this :
function strstr(haystack, needle, bool) {
// Finds first occurrence of a string within another
//
// version: 1103.1210
// discuss at: http://phpjs.org/functions/strstr // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: strstr(‘Kevin van Zonneveld’, ‘van’);
// * returns 1: ‘van Zonneveld’ // * example 2: strstr(‘Kevin van Zonneveld’, ‘van’, true);
// * returns 2: ‘Kevin ‘
// * example 3: strstr(‘name#example.com’, ‘#’);
// * returns 3: ‘#example.com’
// * example 4: strstr(‘name#example.com’, ‘#’, true); // * returns 4: ‘name’
var pos = 0;
haystack += "";
pos = haystack.indexOf(needle); if (pos == -1) {
return false;
} else {
if (bool) {
return haystack.substr(0, pos);
} else {
return haystack.slice(pos);
}
}
}
Source: http://phpjs.org/functions/strstr/
JavaScript String's indexOf() function should meet all your requests
Next example does in JavaScript almost same what you wrote in PHP. Keep in mind that you need to be sure that you have a way to pass $_POST['theaddress'] to your this function. (for example use PHP setcookie() function and then read value in JavaScript code
function reload(fileName) {
// define server address variable
var serverAddress = "https://fbcdn-sphotos-g-a.akamaihd.net/hphotos-ak-ash3/t1.0-9";
// get the filename
var fileName = fileName.indexOf("160x160/");
// set new location based on server address and filename
location.href = serverAddress + fileName;
}
var string='aadsasdsad160x160/saddas'
console.log(string.indexOf('160x160/'))
this will output 10
As usual a solution is already provided when I get back..
function strstr(haystack, needle, before_needle) {
if(haystack.indexOf(needle) >= 0)
return before_needle ? haystack.substr(0, haystack.indexOf(needle))
: haystack.substr(haystack.indexOf(needle));
return false;
}
Try this
String.prototype.strstr = function(search) {
var position = this.indexOf(search);
if (position == -1) {
// not found
return false;
}
return this.slice(position);
};
var x = 'Hello cruel world';
alert(x.strstr('cruel'));
Example here http://jsfiddle.net/bsr3jcuw/
You can create a function like this:
function strstr(haystack, needle, bool) {
var pos = 0;
haystack += '';
pos = haystack.toLowerCase().indexOf((needle + '').toLowerCase());
if (pos == -1) {
return false;
} else {
if (bool) {
return haystack.substr(0, pos);
} else {
return haystack.slice(pos);
}
}
}
Example1:
stristr('Kevin van Zonneveld', 'Van');
returns: 'van Zonneveld'.
Example2:
stristr('Kevin van Zonneveld', 'VAN', true);
returns: 'Kevin '
Reference: http://phpjs.org/functions/stristr/
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am making an Encryption Tool for myself, being a code of JavaScript, inserted into the console( interpreter ) and run, doing what follows( The code is NOT 100% JavaScript, it is an imaginary code that refers to what I want in real JavaScript ):
var encrypt_f = function(z) {
switch(z) {
case "H":
return "0XB";
break;
case "e":
return "EWD";
break;
case "l":
return "FXB";
break;
case "o":
return "#RS";
break;
default:
return "UNK";
break;
} // I will write the rest of words, I got my encryption table
}
var encrypt = function(x) {
// Turn x into an array
// Then make a for loop, to check for every element in the array
// and scan the letter, then, Encrypt the letter, I've provided
// "Hello" as a word to Encrypt, I'll do the rest
// as of:
// var enc = "";
// for(.. i ..) { y = x[i]; enc += encrypt_f(y) + " ";
}
encrypt("Hello");
The encrypt("Hello"); should return 0XB EWD FXB FXB #RS as:
0XB being H
EWD being e
FXB being l - Being wrote twice as there are 2 l's in Hello
#RS being o
NOTE: ONLY JAVASCRIPT, I want the code to be inserted into the browser console to return a string and NOT for sending data to databases or anything like that, the code is NOT written into the script tag, but being inserted into a browser, also, if you can, please make the code plain JavaScript without any external libraries( jQuery )
Just iterate over the string (here with a split of the string and then over the array and with map and the encoding ad callback. The result array is then joined with a space).
var encrypt_f = function (z) {
return { H: '0XB', e: 'EWD', l: 'FXB', o: '#RS' }[z] || 'UNK';
},
encrypt = function (x) {
return x.split('').map(encrypt_f).join(' ');
};
document.write(encrypt("Hello!"));
to map a string to another you can abuse replace()
var mapping = {
"H": "0XB",
"e": "EWD",
"l": "FXB",
"o": "#RS",
default: "UNK"
};
function encrypt(mapping, string){
return string.replace(/[\s\S]/g, function(chr){
//binding and accessing this is faster than a closure
return this[chr] || this.default;
}.bind(mapping));
}
encrypt(mapping, "Hello")
This should work. Jsbin: https://jsbin.com/yiborehuju/edit?js,output
var encrypt = function(x) {
var enc = "";
x = x.split('');
x.forEach(function(l) {
e = encrypt_f(l);
enc += e;
});
return enc;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need help deobfuscating some Javascript. I've been trying to decode it for hours but I've gotten nowhere.
function divulge() {
eval(function (p, a, c, k, e, r) {
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--) r[e(c)] = k[c] || e(c);
k = [
function (e) {
return r[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
}('19 k=["\\N\\U\\O\\V\\P\\F\\a\\W\\a\\Q\\a\\t\\a\\o\\a\\g\\a\\X\\a\\x\\a\\u\\a\\y\\a\\l\\a\\t\\a\\p\\a\\u\\a\\g\\a\\o\\a\\l\\a\\p\\a\\m\\a\\f\\a\\o\\a\\g\\a\\o\\a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|x35|x37|_0xd4b0x3|_0x6159|x65|x39|x61|x38|x63|_0xd4b0x5|x72|x62|x66|x64|x6C|x73|x6F|x70|x67|x68|x69|x74|x31|_0xd4b0x4|x22|x6D|x43|x30|function|_0xd4b0x1|_0xd4b0x2|return|x6E|x6A|x5B|x6B|x5D|x3B|_0xd4b0x6|x20|x3D|x75|x76|x77|x71|x44|x45|x46|x28|x29|String|if|while|45|var|x79|x7A|x41|x2C|x42|x47|x48|x49|x5F|x2B|eval|parseInt|35|29|toString|36|new|RegExp'.split('|'), 0, {
}))
}
I ran it in JSBeautifier and got
function divulge() {
var _0x6159 = ["\x6E\x20\x6A\x3D\x5B\x22\x5C\x75\x5C\x6B\x5C\x66\x5C\x38\x5C\x34\x5C\x76\x5C\x6F\x5C\x64\x5C\x70\x5C\x65\x5C\x66\x5C\x63\x5C\x64\x5C\x34\x5C\x38\x5C\x65\x5C\x63\x5C\x39\x5C\x36\x5C\x38\x5C\x34\x5C\x38\x5C\x63\x5C\x6C\x5C\x36\x5C\x34\x5C\x38\x5C\x36\x5C\x70\x5C\x39\x5C\x36\x5C\x65\x5C\x34\x5C\x6F\x5C\x64\x5C\x77\x5C\x36\x5C\x39\x5C\x34\x5C\x38\x5C\x63\x5C\x6C\x5C\x36\x5C\x34\x5C\x61\x5C\x39\x5C\x71\x5C\x66\x5C\x65\x5C\x39\x5C\x61\x5C\x39\x5C\x78\x5C\x34\x5C\x72\x5C\x61\x5C\x39\x5C\x66\x5C\x61\x5C\x71\x5C\x67\x5C\x36\x5C\x34\x5C\x79\x5C\x6B\x5C\x63\x5C\x38\x5C\x36\x5C\x34\x5C\x64\x5C\x61\x5C\x6C\x5C\x36\x5C\x34\x5C\x7A\x5C\x34\x5C\x38\x5C\x6B\x5C\x61\x5C\x67\x5C\x67\x5C\x34\x5C\x64\x5C\x63\x5C\x65\x5C\x34\x5C\x39\x5C\x36\x5C\x72\x5C\x36\x5C\x61\x5C\x67\x5C\x41\x22\x2C\x22\x5C\x32\x5C\x33\x5C\x42\x5C\x32\x5C\x35\x5C\x6D\x5C\x32\x5C\x35\x5C\x6D\x5C\x32\x5C\x35\x5C\x43\x5C\x32\x5C\x37\x5C\x44\x5C\x32\x5C\x62\x5C\x68\x5C\x32\x5C\x62\x5C\x68\x5C\x32\x5C\x35\x5C\x37\x5C\x32\x5C\x33\x5C\x73\x5C\x32\x5C\x33\x5C\x35\x5C\x32\x5C\x33\x5C\x69\x5C\x32\x5C\x33\x5C\x73\x5C\x32\x5C\x33\x5C\x69\x5C\x32\x5C\x62\x5C\x69\x5C\x32\x5C\x33\x5C\x37\x5C\x32\x5C\x33\x5C\x45\x5C\x32\x5C\x33\x5C\x46\x5C\x32\x5C\x35\x5C\x37\x5C\x32\x5C\x33\x5C\x37\x5C\x32\x5C\x35\x5C\x37\x5C\x32\x5C\x33\x5C\x37\x5C\x32\x5C\x62\x5C\x69\x5C\x32\x5C\x33\x5C\x68\x5C\x32\x5C\x35\x5C\x62\x5C\x32\x5C\x33\x5C\x35\x5C\x32\x5C\x62\x5C\x68\x5C\x32\x5C\x35\x5C\x37\x5C\x32\x5C\x33\x5C\x74\x5C\x32\x5C\x33\x5C\x37\x5C\x32\x5C\x35\x5C\x62\x5C\x32\x5C\x33\x5C\x74\x5C\x32\x5C\x35\x5C\x6D\x5C\x32\x5C\x35\x5C\x37\x22\x5D\x3B\x47\x28\x6A\x5B\x30\x5D\x29\x3B\x6E\x20\x48\x3D\x49\x28\x6A\x5B\x31\x5D\x29\x3B", "\x7C", "\x73\x70\x6C\x69\x74", "\x7C\x7C\x78\x32\x35\x7C\x78\x33\x36\x7C\x78\x32\x30\x7C\x78\x33\x37\x7C\x78\x36\x35\x7C\x78\x33\x33\x7C\x78\x37\x33\x7C\x78\x37\x32\x7C\x78\x36\x31\x7C\x78\x33\x32\x7C\x78\x36\x46\x7C\x78\x36\x45\x7C\x78\x37\x34\x7C\x78\x36\x39\x7C\x78\x36\x43\x7C\x78\x34\x36\x7C\x78\x34\x35\x7C\x5F\x30\x78\x32\x63\x36\x66\x7C\x78\x36\x38\x7C\x78\x36\x44\x7C\x78\x33\x34\x7C\x76\x61\x72\x7C\x78\x37\x35\x7C\x78\x36\x33\x7C\x78\x36\x32\x7C\x78\x37\x36\x7C\x78\x33\x39\x7C\x78\x33\x35\x7C\x78\x35\x34\x7C\x78\x36\x36\x7C\x78\x36\x34\x7C\x78\x37\x39\x7C\x78\x37\x37\x7C\x78\x34\x39\x7C\x78\x32\x31\x7C\x78\x33\x38\x7C\x78\x33\x30\x7C\x78\x34\x31\x7C\x78\x33\x31\x7C\x78\x34\x34\x7C\x61\x6C\x65\x72\x74\x7C\x73\x65\x63\x72\x65\x74\x6F\x73\x7C\x75\x6E\x65\x73\x63\x61\x70\x65", "", "\x66\x72\x6F\x6D\x43\x68\x61\x72\x43\x6F\x64\x65", "\x72\x65\x70\x6C\x61\x63\x65", "\x5C\x77\x2B", "\x5C\x62", "\x67"];
eval(function (_0xd4b0x1, _0xd4b0x2, _0xd4b0x3, _0xd4b0x4, _0xd4b0x5, _0xd4b0x6) {
_0xd4b0x5 = function (_0xd4b0x3) {
return (_0xd4b0x3 < _0xd4b0x2 ? _0x6159[4] : _0xd4b0x5(parseInt(_0xd4b0x3 / _0xd4b0x2))) + ((_0xd4b0x3 = _0xd4b0x3 % _0xd4b0x2) > 35 ? String[_0x6159[5]](_0xd4b0x3 + 29) : _0xd4b0x3.toString(36))
};
if (!_0x6159[4][_0x6159[6]](/^/, String)) {
while (_0xd4b0x3--) {
_0xd4b0x6[_0xd4b0x5(_0xd4b0x3)] = _0xd4b0x4[_0xd4b0x3] || _0xd4b0x5(_0xd4b0x3)
};
_0xd4b0x4 = [
function (_0xd4b0x5) {
return _0xd4b0x6[_0xd4b0x5]
}];
_0xd4b0x5 = function () {
return _0x6159[7]
};
_0xd4b0x3 = 1
};
while (_0xd4b0x3--) {
if (_0xd4b0x4[_0xd4b0x3]) {
_0xd4b0x1 = _0xd4b0x1[_0x6159[6]](new RegExp(_0x6159[8] + _0xd4b0x5(_0xd4b0x3) + _0x6159[8], _0x6159[9]), _0xd4b0x4[_0xd4b0x3])
}
};
return _0xd4b0x1
}(_0x6159[0], 45, 45, _0x6159[3][_0x6159[2]](_0x6159[1]), 0, {}));
}
I'm pretty lost at this point. Is the first code not obfuscated? I don't have much experience in programming, it's a part of a computer science challenge I've been trying to do. I also tried replacing function in line 1 with alert and it said there's a missing semicolon but I'm not sure where.
Here's a quick tutorial on deobfuscating it. I will not go into too much detail because this was a challenge you are supposed to solve afterall.
Take the original code and look at its structure. It basically is of the form
function divulge() {
eval(function(...) {
/* nobody cares what happens here */
// now this is interesting, because p will contain the string that eval() will execute!
return p;
}(...));
}
It should be fairly obvious now how to learn what this code will execute rather than having it actually execute: p will get evaled, so just intercept it. This will show that it's just more code (obviously).
So let's start over! Looking at the new code, after beautifying it, we will see that the structure is basically the same. So someone is trying to be sneaky by obfuscating the code several times. Too bad we already deobfuscated it once, so we just repeat the entire procedure.
After the second time, we get code of the structure
var _0x2c6f = ["..."];
alert(_0x2c6f[0]);
var secretos = unescape(_0x2c6f[1]);
This will alert the following text:
This function stores some secret under some arbitrary variable whose name I shall not reveal!
And finally, secretos contains a link. However, I will censor the link here for multiple reasons:
http://signin.**********.org/secrets
How can I know that how much data is transferred over wire in terms of size in kilobytes, megabytes?
Take for example
{
'a': 1,
'b': 2
}
How do I know what is the size of this payload is and not the length or items in the object
UPDATE
content-encoding:gzip
content-type:application/json
Transfer-Encoding:chunked
vary:Accept-Encoding
An answer to the actual question should include the bytes spent on the headers and should include taking gzip compression into account, but I will ignore those things.
You have a few options. They all output the same answer when run:
If Using a Browser or Node (Not IE)
const size = new TextEncoder().encode(JSON.stringify(obj)).length
const kiloBytes = size / 1024;
const megaBytes = kiloBytes / 1024;
If you need it to work on IE, you can use a pollyfill
If Using Node
const size = Buffer.byteLength(JSON.stringify(obj))
(which is the same as Buffer.byteLength(JSON.stringify(obj), "utf8")).
Shortcut That Works in IE, Modern Browsers, and Node
const size = encodeURI(JSON.stringify(obj)).split(/%..|./).length - 1;
That last solution will work in almost every case, but that last solution will throw a URIError: URI malformed exception if you feed it input containing a string that should not exist, like let obj = { partOfAnEmoji: "👍🏽"[1] }. The other two solutions I provided will not have that weakness.
(Credits: Credit for the first solution goes here.
Credit for the second solution goes to the utf8-byte-length package (which is good, you could use that instead).
Most of the credit for that last solution goes to here, but I simplified it a bit.
I found the test suite of the utf8-byte-length package super helpful, when researching this.)
For ascii, you can count the characters if you do...
JSON.stringify({
'a': 1,
'b': 2
}).length
If you have special characters too, you can pass through a function for calculating length of UTF-8 characters...
function lengthInUtf8Bytes(str) {
// Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
var m = encodeURIComponent(str).match(/%[89ABab]/g);
return str.length + (m ? m.length : 0);
}
Should be accurate...
var myJson = JSON.stringify({
'a': 1,
'b': 2,
'c': 'Máybë itß nºt that sîmple, though.'
})
// simply measuring character length of string is not enough...
console.log("Inaccurate for non ascii chars: "+myJson.length)
// pass it through UTF-8 length function...
console.log("Accurate for non ascii chars: "+ lengthInUtf8Bytes(myJson))
/* Should echo...
Inaccurate for non ascii chars: 54
Accurate for non ascii chars: 59
*/
Working demo
Here is a function which does the job.
function memorySizeOf(obj) {
var bytes = 0;
function sizeOf(obj) {
if(obj !== null && obj !== undefined) {
switch(typeof obj) {
case 'number':
bytes += 8;
break;
case 'string':
bytes += obj.length * 2;
break;
case 'boolean':
bytes += 4;
break;
case 'object':
var objClass = Object.prototype.toString.call(obj).slice(8, -1);
if(objClass === 'Object' || objClass === 'Array') {
for(var key in obj) {
if(!obj.hasOwnProperty(key)) continue;
sizeOf(obj[key]);
}
} else bytes += obj.toString().length * 2;
break;
}
}
return bytes;
};
function formatByteSize(bytes) {
if(bytes < 1024) return bytes + " bytes";
else if(bytes < 1048576) return(bytes / 1024).toFixed(3) + " KiB";
else if(bytes < 1073741824) return(bytes / 1048576).toFixed(3) + " MiB";
else return(bytes / 1073741824).toFixed(3) + " GiB";
};
return formatByteSize(sizeOf(obj));
};
console.log(memorySizeOf({"name": "john"}));
I got the snippet from following URL
https://gist.github.com/zensh/4975495
Buffer.from(JSON.stringify(obj)).length will give you the number of bytes.
JSON-objects are Javascript-objects, this SO question already shows a way to calculate the rough size. <- See Comments/Edits
EDIT: Your actual question is quite difficult as even if you could access the headers, content-size doesn't show the gzip'ed value as far as I know.
If you're lucky enough to have a good html5 browser, this contains a nice piece of code:
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
console.log(percentComplete);
}
}
Therefore the following should work (can't test right now):
var xhr = new window.XMLHttpRequest();
if (xhr.lengthComputable) {
alert(xhr.total);
}
Note that XMLHttpRequest is native and doesn't require jQuery.
Next EDIT:
I found a kind-of duplicate (slightly diffrent question, pretty much same answer). The important part for this question is
content_length = jqXHR.getResponseHeader("X-Content-Length");
Where jqXHR is your XmlHttpRequest.
I don't get it.
I can't increment the Tweet-ID ...
Here is a demo: http://jsbin.com/idupoq/1/edit
glb = {};
glb.lastTweetId = 0;
getTweets();
function getTweets()
{
console.info('# LAST ID');
console.log(glb.lastTweetId);
console.info('# TEST 1');
glb.lastTweetId++;
console.log(glb.lastTweetId);
console.info('# TEST 2');
glb.lastTweetId = glb.lastTweetId+1;
console.log(glb.lastTweetId);
console.info('# TEST 3, OK IS INT BUT PARSE AGAIN ');
glb.lastTweetId = parseInt(glb.lastTweetId);
glb.lastTweetId++;
console.log(glb.lastTweetId);
$.getJSON('http://search.twitter.com/search.json?q=%23wwm&since_id='+glb.lastTweetId+'&include_entities=true&result_type=mixed&lang=de&callback=?', function(data, textStatus)
{
if(data.results.length > 0)
{
glb.lastTweetId = data.results[0]['id'];
}
glb.tm= setTimeout('getTweets();',5000);
});
}
Thanks in advance!
This happens because the received ID is out of range of Number format, e.g.
271567725082578940 + 1 = 271567725082578940
You should use special libraries to work with large numbers. Some examples:
https://github.com/jtobey/javascript-bignum
http://jsfromhell.com/classes/bignumber
As others have said already, it is because of Number cannot express 271567725082578941. If all you ever want to do to this number is to increase it by one, then the following function should be all you need:
function stringInc(v){
var digits = v.toString().split('');
var i = digits.length-1;
while (digits[i]==9 && i>0){
digits[i] = 0;
i--;
}
digits[i] = 1+parseInt(digits[i]);
return digits.join('');
}
If you expect to want to do something more with the number, then you might be better off using a BigNumber library as suggested by VisioN.
Either way, you should note that you cannot read the tweet id from data.results[0]['id'], because that is interpreted as a Number and rounded to 271567725082578940. You need to use data.results[0]['id_str'].
See updated jsbin here: http://jsbin.com/idupoq/19/. Notice the console is logging the result from the server:
...
"geo":null,
"id": 271580395022217200,
"id_str":"271580395022217216",
"iso_language_code":"de"
...
So the value 271567725082578940 that you have been observing is incorrect as well.
Dirty but short
http://jsbin.com/idupoq/18/edit
glb.lastTweetId = ''+data.results[0]['id']+'';
var lastTwoDig = parseInt(glb.lastTweetId.substr(glb.lastTweetId.length-2));
var startDigit = glb.lastTweetId.substring(0, glb.lastTweetId.length-2);
lastTwoDig++;
if(lastTwoDig==01){ lastTwoDig = '01'; }
console.log(glb.lastTweetId);
console.log(' '+startDigit+''+lastTwoDig+' ');
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have seen "https://stackoverflow.com/questions/1385335/how-to-generate-function-call-graphs-for-javascript", and tried it. It works well, if you want to get an abstract syntax tree.
Unfortunately Closure Compiler only seems to offer --print_tree, --print_ast and --print_pass_graph. None of them are useful for me.
I want to see a chart of which function calls which other functions.
code2flow does exactly this. Full disclosure, I started this project
To run
$ code2flow source1.js source2.js -o out.gv
Then, open out.gv with graphviz
Edit: For now, this project is unmaintained. I would suggest trying out a different solution before using code2flow.
If you filter the output of closure --print_tree you get what you want.
For example take the following file:
var fib = function(n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
};
console.log(fib(fib(5)));
Filter the output of closure --print_tree
NAME fib 1
FUNCTION 1
CALL 5
NAME fib 5
SUB 5
NAME a 5
NUMBER 1.0 5
CALL 5
NAME fib 5
SUB 5
NAME a 5
NUMBER 2.0 5
EXPR_RESULT 9
CALL 9
GETPROP 9
NAME console 9
STRING log 9
CALL 9
CALL 9
NAME fib 9
CALL 9
CALL 9
NAME fib 9
NUMBER 5.0 9
And you can see all the call statements.
I wrote the following scripts to do this.
./call_tree
#! /usr/bin/env sh
function make_tree() {
closure --print_tree $1 | grep $1
}
function parse_tree() {
gawk -f parse_tree.awk
}
if [[ "$1" = "--tree" ]]; then
make_tree $2
else
make_tree $1 | parse_tree
fi
parse_tree.awk
BEGIN {
lines_c = 0
indent_width = 4
indent_offset = 0
string_offset = ""
calling = 0
call_indent = 0
}
{
sub(/\[source_file.*$/, "")
sub(/\[free_call.*$/, "")
}
/SCRIPT/ {
indent_offset = calculate_indent($0)
root_indent = indent_offset - 1
}
/FUNCTION/ {
pl = get_previous_line()
if (calculate_indent(pl) < calculate_indent($0))
print pl
print
}
{
lines_v[lines_c] = $0
lines_c += 1
}
{
indent = calculate_indent($0)
if (indent <= call_indent) {
calling = 0
}
if (calling) {
print
}
}
/CALL/ {
calling = 1
call_indent = calculate_indent($0)
print
}
/EXPR/{
line_indent = calculate_indent($0)
if (line_indent == root_indent) {
if ($0 !~ /(FUNCTION)/) {
print
}
}
}
function calculate_indent(line) {
match(line, /^ */)
return int(RLENGTH / indent_width) - indent_offset
}
function get_previous_line() {
return lines_v[lines_c - 1]
}
I finally managed this using UglifyJS2 and Dot/GraphViz, in a sort of combination of the above answer and the answers to the linked question.
The missing part, for me, was how to filter the parsed AST. It turns out that UglifyJS has the TreeWalker object, which basically applys a function to each node of the AST. This is the code I have so far:
//to be run using nodejs
var UglifyJS = require('uglify-js')
var fs = require('fs');
var util = require('util');
var file = 'path/to/file...';
//read in the code
var code = fs.readFileSync(file, "utf8");
//parse it to AST
var toplevel = UglifyJS.parse(code);
//open the output DOT file
var out = fs.openSync('path/to/output/file...', 'w');
//output the start of a directed graph in DOT notation
fs.writeSync(out, 'digraph test{\n');
//use a tree walker to examine each node
var walker = new UglifyJS.TreeWalker(function(node){
//check for function calls
if (node instanceof UglifyJS.AST_Call) {
if(node.expression.name !== undefined)
{
//find where the calling function is defined
var p = walker.find_parent(UglifyJS.AST_Defun);
if(p !== undefined)
{
//filter out unneccessary stuff, eg calls to external libraries or constructors
if(node.expression.name == "$" || node.expression.name == "Number" || node.expression.name =="Date")
{
//NOTE: $ is from jquery, and causes problems if it's in the DOT file.
//It's also very frequent, so even replacing it with a safe string
//results in a very cluttered graph
}
else
{
fs.writeSync(out, p.name.name);
fs.writeSync(out, " -> ");
fs.writeSync(out, node.expression.name);
fs.writeSync(out, "\n");
}
}
else
{
//it's a top level function
fs.writeSync(out, node.expression.name);
fs.writeSync(out, "\n");
}
}
}
if(node instanceof UglifyJS.AST_Defun)
{
//defined but not called
fs.writeSync(out, node.name.name);
fs.writeSync(out, "\n");
}
});
//analyse the AST
toplevel.walk(walker);
//finally, write out the closing bracket
fs.writeSync(out, '}');
I run it with node, and then put the output through
dot -Tpng -o graph_name.png dot_file_name.dot
Notes:
It gives a pretty basic graph - only black and white and no formatting.
It doesn't catch ajax at all, and presumably not stuff like eval or with either, as others have mentioned.
Also, as it stands it includes in the graph: functions called by other functions (and consequently functions that call other functions), functions that are called independantly, AND functions that are defined but not called.
As a result of all this, it may miss things that are relevant, or include things that are not. It's a start though, and appears to accomplish what I was after, and what led me to this question in the first place.
https://github.com/mishoo/UglifyJS
gives access to an ast in javascript.
ast.coffee
util = require 'util'
jsp = require('uglify-js').parser
orig_code = """
var a = function (x) {
return x * x;
};
function b (x) {
return a(x)
}
console.log(a(5));
console.log(b(5));
"""
ast = jsp.parse(orig_code)
console.log util.inspect ast, true, null, true