toSrc
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 = ; // Primitives /////////////////////////////////////// ; // = '1' ; // = 'true' ; // = 'undefined' ; // = null ; // = '"1"' ; // = '"1"' toSrc always uses double-quotes // Constants /////////////////////////////////////// ; // = 'Math.PI' ; // = 'NaN' // RegExp /////////////////////////////////////// ; // = '/myRegEx/gi' ; // = '/myRegEx/' // Date /////////////////////////////////////// ; // = 'new Date(<the time of creation in ms>)' // Functions /////////////////////////////////////// { var test = "hello"; } ; // = 'function testFunc() {\n var test = "hello";\n}' ; // = 'String', native functions don't expose the source code // Arrays /////////////////////////////////////// ; // = '[1, 2, "3"]' ; // = '[1, 2, undefined]' because the depth // is 1 by default ; // = '[1, 2, ["a", "b", "c"]]' // Objects /////////////////////////////////////// ; // = '{"regEx": /regex/gi, "anotherObj": undefined}' // anotherObj is undefined because the depth is 1 by default. ; // = '{"regEx": /regex/gi, "anotherObj": {"test": "test"}}'
For more examples check out test/test.js
API
toSrc(obj: *, depth: Number): String
-
obj:
The object to stringify. Can also be a primitive like1
ortrue
. -
{Number=1} depth:
The depth to go. All nested structures like objects or arrays deeper than this will be undefined. Defaults to 1, meaning that every object or array withinobj
will be undefined by default.
Usage
In node.js
var toSrc = ; ;
In the browser
Just call toSrc(obj, depth);
Notes
- Circular references will be undefined. No error is thrown, but a warning is logged.
- All math constants are restored to their source representation, e.g.:
toSrc(Math.PI); // = 'Math.PI' instead of 3.14...
- All dates are restored to their original time of creation, e.g.:
toSrc(new Date()) // = 'new Date(<time of creation in ms>)'
- Dynamic regular expressions created via
new RegExp()
will not be dynamic anymore.toSrc(new RegExp(someString))
will return'/<value of someString>/'
instead of'new RegExp(someString)'
Feel free to modify the code to meet your needs.
License
MIT