jhnns / toSrc

Turns every JavaScript object or primitive into valid source code that can be evaled again.
MIT License
19 stars 3 forks source link

toSrc Build Status

Turns every JavaScript object or primitive into valid source code that can be evaled again.

You can use it to serialize classes, modules or other programming objects and reuse them in an other environment such as a browser. JSON.stringify doesnt work with programming objects (that contain functions, dates, etc.) because they're no legal JSONs.


Installation

npm install toSrc


Examples


    var toSrc = require("toSrc");

    // Primitives
    ///////////////////////////////////////
    toSrc(1); // = '1'
    toSrc(true); // = 'true'
    toSrc(undefined); // = 'undefined'
    tOSrc(null); // = null
    toSrc("1"); // = '"1"'
    toSrc('1'); // = '"1"' toSrc always uses double-quotes    

    // Constants
    ///////////////////////////////////////
    toSrc(Math.PI); // = 'Math.PI'
    toSrc(NaN); // = 'NaN'

    // RegExp
    ///////////////////////////////////////
    toSrc(/myRegEx/gi); // = '/myRegEx/gi'
    toSrc(new RegExp("myRegEx")); // = '/myRegEx/'

    // Date
    ///////////////////////////////////////
    toSrc(new Date()); // = 'new Date(<the time of creation in ms>)'

    // Functions
    ///////////////////////////////////////
    function testFunc() {
        var test = "hello";
    }
    toSrc(testFunc); // = 'function testFunc() {\n    var test = "hello";\n}'
    toSrc(String); // = 'String', native functions don't expose the source code

    // Arrays
    ///////////////////////////////////////
    toSrc([1, 2, "3"]); // = '[1, 2, "3"]'
    toSrc([1, 2, ["a", "b", "c"]]); // = '[1, 2, undefined]' because the depth
                                    // is 1 by default
    toSrc([1, 2, ["a", "b", "c"]], 2); // = '[1, 2, ["a", "b", "c"]]'

    // Objects
    ///////////////////////////////////////
    toSrc({
        regEx: /regex/gi,
        anotherObj: {
            test: "test"
        }
    });
    // = '{"regEx": /regex/gi, "anotherObj": undefined}'
    // anotherObj is undefined because the depth is 1 by default.
    toSrc({
        "regEx": /regex/gi,
        "anotherObj": {
            "test": "test"
        }
    }, 2);
    // = '{"regEx": /regex/gi, "anotherObj": {"test": "test"}}'

For more examples check out test/test.js


API

toSrc(obj: *, depth: Number): String


Usage

In node.js

var toSrc = require("toSrc");

toSrc(obj, depth);

In the browser

Just call toSrc(obj, depth);


Notes

Feel free to modify the code to meet your needs.


License

MIT