<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Серый форум &mdash; WSH/JS/VBS: Firebug console для WSH]]></title>
		<link>https://forum.script-coding.com/viewtopic.php?id=8403</link>
		<atom:link href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=8403&amp;type=rss" rel="self" type="application/rss+xml" />
		<description><![CDATA[Недавние сообщения в теме «WSH/JS/VBS: Firebug console для WSH».]]></description>
		<lastBuildDate>Tue, 18 Jun 2013 08:46:42 +0000</lastBuildDate>
		<generator>PunBB</generator>
		<item>
			<title><![CDATA[WSH/JS/VBS: Firebug console для WSH]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=73031#p73031</link>
			<description><![CDATA[<p>Имитация известного плагина Firebug. Этот код можно было бы считать избыточным, так как WSH имеет достаточно универсальных средств для визуализации сообщений. Тем не менее, я реализовал этот код, подстроив его под среду. </p><p>Скрипт реализует следующие возможности:</p><p>Вывод различных типов сообщений:<br /></p><div class="quotebox"><blockquote><p>console.log(object[, object, ...])<br />console.debug(object[, object, ...])<br />console.info(object[, object, ...])<br />console.warn(object[, object, ...])<br />console.error(object[, object, ...])</p></blockquote></div><p>Проверка: если выражение false, выводит сообщение<br /></p><div class="quotebox"><blockquote><p>console.assert(expression[, object, ...])</p></blockquote></div><p>Запуск/остановка именованного таймера и вывод прошедшего времени<br /></p><div class="quotebox"><blockquote><p>console.time(name)<br />console.timeEnd(name)</p></blockquote></div><p>Примеры<br /></p><div class="quotebox"><blockquote><p>// простой вывод<br />console.log(&quot;To be or not to be&quot;);</p><p>// форматированный вывод в стиле printf<br />// выведет строку &quot;12 monkeys&quot;<br />console.log(&quot;%d %s&quot;, 12, &quot;monkeys&quot;);</p><p>// вывод сообщения если выражение ложно<br />console.assert(false);</p><p>// замерить время исполнения<br />console.time(&#039;loop&#039;);<br />for (var i = 0; i &lt; 1000; i++) {}<br />console.timeEnd(&#039;loop&#039;);</p></blockquote></div><p>Предусмотрено расширение возможностей, например, изменить формат выводимой строки, или организовать вывод сообщений в диалоговых окнах<br /></p><div class="codebox"><pre><code>
var title = {
    16: &#039;ERROR&#039;, 
    48: &#039;WARNING&#039;, 
    64: &#039;INFO&#039;, 
    0: &#039;INFO&#039;
};
console.fn.print = function(msgType, msg)
{
    WScript.StdOut.WriteLine(new Date() + &#039;: &#039; + title[msgType] + &#039;: &#039; + msg);
};
</code></pre></div><div class="codebox"><pre><code>
Function CustomPrint(MsgType, Msg)
    MsgBox Msg, MsgType
End Function

Set console.fn.print = GetRef(&quot;CustomPrint&quot;)
</code></pre></div><p>Последний пример показывает, что консоль совместима с VBScript.</p><p>Актуальная версия скрипта<br /><a href="http://code.google.com/p/jsxt/source/browse/trunk/js/win32/console.js">http://code.google.com/p/jsxt/source/br … console.js</a></p><p>Исходник<br /></p><div class="codebox"><pre><code>
(function()
{

    // Be sure to prevent defining it twice
    if ( this.console &amp;&amp; console.fn ) {
        return;
    }


    // The main object
    this.console = {};


    // Details for the complex object
    // If JSON object is defined JSON.stringify will be used
    var _inspect = typeof JSON != &#039;undefined&#039; &amp;&amp; typeof JSON.stringify == &#039;function&#039; 
        ? 
        function(object)
        {
            return object &amp;&amp; typeof object == &#039;object&#039; ? JSON.stringify(object) : object;
        } 
        : 
        function(object)
        {
            return object;
        };

    // This regular expression is used to recongnize a formatting string 
    var reFormat = /%%|%(\d+)?([idfxso])/g;

    // Checks that the object is a formatting string
    var _isFormat = function(object)
    {
        return String(object).match(reFormat);
    };

    var _formatters = {};
    _formatters.i = function(v) { return Number(v).toFixed(0); };
    _formatters.d = 
    _formatters.f = function(v) { return Number(v).toString(10); };
    _formatters.x = function(v) { return Number(v).toString(16); }, 
    _formatters.o = _inspect;
    _formatters.s = function(v) { return String(v); };

    // The formatting function immitating C-like &quot;printf&quot;
    var _format = function(pattern, objects)
    {
        var i = 0;
        return pattern.replace(reFormat, function(format, width, id)
        {
            if ( format == &#039;%%&#039; ) {
                return &#039;%&#039;;
            }

            i++;

            var r = _formatters[id](objects[i]);

            return r;
        });
    };

    // The printing function
    var _print = function(msgType, msg)
    {
        WScript.Echo(msg);
    };


    // The core function
    var printMsg = function(msgType, objects)
    {
        // Get the actual configuration of the console
        var fn = console.fn;
        var sep = fn.separator || &#039; &#039;;

        var result;

        if ( fn.isFormat(objects[0]) ) {
            //result = fn.format(objects[0], Array.prototype.slice.call(objects, 1));
            result = fn.format(objects[0], objects);
        } else {
            result = [];
            for (var i = 0; i &lt; objects.length; i++) {
                result.push(fn.inspect(objects[i]));
            }
            result = result.join(sep);
        }

        fn.print(msgType, result);
    };


    var log = function()
    {
        printMsg(0, arguments);
    };

    var debug = log;

    var info = function()
    {
        printMsg(64, arguments);
    };

    var warn = function()
    {
        printMsg(48, arguments);
    };

    var error = function()
    {
        printMsg(16, arguments);
    };


    // If the expression is false, the rest of arguments will be logged in 
    // the console
    var assert = function(expr)
    {
        if ( expr ) {
            return;
        }
        error.apply(console, arguments.length &lt; 2 ? [&#039;Assertion error&#039;] : Array.prototype.slice.call(arguments, 1));
    };


    // Processing of timers start/stop
    var timeNames = {};

    var timeStart = function(name)
    {
        if ( ! name ) {
            return;
        }

        timeNames[name] = new Date();
        log(name + &#039;: Timer started&#039;);
    };

    var timeEnd = function(name)
    {
        if ( ! name || ! timeNames.hasOwnProperty(name) ) {
            return;
        }

        var t = new Date() - timeNames[name];
        delete timeNames[name];

        log(name + &#039;: &#039; + t + &#039;ms&#039;);
    };


    // Stub for the non-implemented methods
    var noop = function()
    {
    };


    console = {
        // Implemented methods
        log: log, 
        debug: debug, 
        info: info, 
        warn: warn, 
        error: error, 

        assert: assert, 

        time: timeStart, 
        timeEnd: timeEnd, 

        // Not implemented methods
        clear: noop, 

        dir: noop, 
        dirxml: noop, 

        group: noop, 
        groupCollapsed: noop, 
        groupEnd: noop, 

        profile: noop, 
        profileEnd: noop, 

        table: noop, 

        trace: noop, 

        // Customizing of the console
        fn: {
            isFormat: _isFormat, 
            format: _format, 
            inspect: _inspect, 
            print: _print, 
            separator: &#039; &#039;
        }
    };

})();

</code></pre></div>]]></description>
			<author><![CDATA[null@example.com (Rumata)]]></author>
			<pubDate>Tue, 18 Jun 2013 08:46:42 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=73031#p73031</guid>
		</item>
	</channel>
</rss>
