toSource converts JavaScript objects back to source


toSource is a super simple function that converts JavaScript objects back to source code.

Motivation: JSON doesn't support serializing functions, dates, or regular expressions. I wanted a quick and simple way to push trusted data structures with code from Node down to the browser.

This should make it easier to share code and modules between the server and client.

npm install tosource

The following code:

var toSource = require('tosource')
    [ 4, 5, 6, "hello", {
        foofunction(bar) {
            console.log("woo! a is "+a)
            console.log("and bar is "+bar)
    new Date("Wed, 09 Aug 1995 00:00:00 GMT")]


[ 4,
  { "1":4,
    foo:function (bar) {
            console.log("woo! a is "+a)
            console.log("and bar is "+bar)
        } },
  new Date(807926400000) ]

See test.js for more examples.

  • Numbers
  • Strings
  • Array literals
  • object literals
  • function
  • RegExp literals
  • Dates
  • true
  • false
  • undefined
  • null
  • NaN
  • Infinity
  • Functions are serialized with func.toString(), no closure properties are serialized
  • Multiple references to the same object become copies
  • Circular references are encoded as {$circularReference:1}

toSource is open source software under the zlib license.