TermsOfService TermsOfService - 9 months ago 52
Javascript Question

Unexpected behaviour of console.log function

I am creating project in Node.js to download files from website. My project works properly, but when I try to display download status, it doesn't work as I expect. This is the command I use

console.log(percent + '%downloaded from', url);

But, instead of displaying
42% downloaded from
it displays
42NaNownloaded from
. Why it displays
insead of percents and url? How can I fix it?


Why it displays NaN insead of percents and url?

Because console.log works very similar to C function printf. If you pass string which contains % character as the first argument, it will search for substitutive string in other arguments. Sequence %d represents 32-bit signed integer in C. Console will replace it with the second argument converted to number. Because your url cannot be parsed as a number, it puts NaN instead (not-a-number).

How can I fix it?

You have to avoid console.log function. For Node.js it's simple - use process.stdout.write instead. For browsers, you need to override console.log function, so you can force it not to substitute %d or %s.

console.log = (function(a){
    return function(){
        var b = [], c;
        for(c in arguments) b[c] = arguments[c];
        a.apply(console, b.map(function(a){
            return typeof a == 'string' ? a.replace(/\%/g, '%\x00') : a;

Also, you can do it in Node.js too. After overriding, if you type console.log(%d, 1) it will log %d 1 instead of 1.