- Saved searches
- Use saved searches to filter your results more quickly
- License
- piranna/tosource-polyfill
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- Readme.md
- About
- Node.js tosource toSource is a super simple function that converts JavaScript objects back to source code.
- Introduction
- Installation
- Examples
- Supported Types
- Notes
- License
- More Examples
- Related
- Object.prototype.toSource()
- Syntax
- Return value
- Description
- Overriding the toSource() method
- Built-in toSource() methods
- Limitations on cyclical objects
- Examples
- Using toSource()
- Specifications
- Browser compatibility
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Converts JavaScript objects to source
License
piranna/tosource-polyfill
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
Readme.md
toSource polyfill that converts JavaScript objects back to source code
This module set on objects prototype the Mozilla toSource() function that allow to get a source code representation of an object. It also has a helper function that allow to serialize some extra objects like null or undefined .
npm install tosource-polyfill
var toSource = require('tosource-polyfill') console.log(toSource( [ 4, 5, 6, "hello", a:2, 'b':3, '1':4, 'if':5, yes:true, no:false, nan:NaN, infinity:Infinity, 'undefined':undefined, 'null':null, foo: function(bar) console.log("woo! a is "+a) console.log("and bar is "+bar) > >, /we$/gi, new Date("Wed, 09 Aug 1995 00:00:00 GMT")] ))
[ 4, 5, 6, "hello", "1":4, a:2, b:3, "if":5, yes:true, no:false, nan:NaN, infinity:Infinity, "undefined":undefined, "null":null, foo:function (bar) console.log("woo! a is "+a) console.log("and bar is "+bar) > >, /we$/gi, new Date(807926400000) ]
- 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
toSource is open source software under the zlib license.
About
Converts JavaScript objects to source
Node.js tosource toSource is a super simple function that converts JavaScript objects back to source code.
toSource is a super simple function that converts JavaScript objects back to source code.
Introduction
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.
Installation
Examples
import toSource from 'tosource'; console.log(/* w w w .d e m o2 s. c om */ toSource([ 4, 5, 6, 'hello', < a: 2, b: 3, '1': 4, if: 5, yes: true, no: false, nan: NaN, infinity: Infinity, undefined: undefined, null: null, foo: function (bar) < console.log('woo! a is ' + a); console.log('and bar is ' + bar); >, >, /we$/gi, new Date('Wed, 09 Aug 1995 00:00:00 GMT'), ]), );
[ 4,// w w w . de m o 2 s . co m 5, 6, "hello", < 1:4, a:2, b:3, "if":5, yes:true, no:false, nan:NaN, infinity:Infinity, "undefined":undefined, "null":null, foo:function (bar) < console.log('woo! a is ' + a); console.log('and bar is ' + bar); >>, /we$/gi, new Date(807926400000) ]
See tosource.test.ts for more examples.
Supported Types
- numbers (including NaN, Infinity, and -0)
- strings
- Arrays (including sparse arrays)
- object literals
- function
- RegExp instances
- Date instances
- Map
- Set
- true / false
- undefined
- null
Notes
- Functions are serialized with func.toString(), no closure properties are serialized
- Multiple references to the same object become copies
- Circular references are encoded as
License
toSource is open source software under the zlib license.
The repository of tosource is in Gitgithub.com/marcello3d/node-tosource
Install Command
To install tosource use the following command:
More Examples
The following examples shows how to use Node.js library tosource.
import CleanCSS from 'clean-css'; import toSource from 'tosource'; export default function createOutro ( definition, indent = '' ) < const css = definition.css ? new CleanCSS().minify( definition.css ).styles : ''; const imports = definition.imports.map( getImportKeyValuePair ); let outro = [// w w w . de m o 2 s . c o m `$component.exports.template = $'' )>;` ]; if ( css ) outro.push( `$component.exports.css = $ ;` ); if ( imports.length ) outro.push( `$component.exports.components = < $ ', ')>>;` ); return outro.join( '\n' ); > function getImportKeyValuePair ( imported, i ) < return `$ name)>: __import$__`; > function stringify ( key ) < if ( /^[a-zA-Z$_][a-zA-Z$_0-9]*$/.test( key ) ) < return key; > return JSON.stringify( key ); >
var rcu = require('rcu'); var Ractive = require('ractive'); var CleanCSS = require('clean-css'); var toSource = require('tosource'); rcu.init(Ractive);/* w w w. d e m o 2 s . c o m */ module.exports = function(source) < this.cacheable(); var definition = rcu.parse(source); return '' + "var Ractive = require('ractive');\n" + 'var component = module;\n' + ( definition.script ? definition.script + '\n' : '' ) + 'component.exports.template = ' + toSource( definition.template, null, '' ) + ';\n' + ( definition.css ? 'component.exports.css = ' + JSON.stringify(new CleanCSS().minify(definition.css).styles) + ';\n' : '' ) + ( definition.imports.length ? 'component.exports.components = + definition.imports.map(getImportKeyValuePair).join( ', ' ) + '>;\n' : '' ) + 'module.exports = Ractive.extend(component.exports);\n'; >; function getImportKeyValuePair(imported, i) < return stringify(imported.name) + ": require('" + imported.href + "')"; > function stringify(key) < if ( /^[a-zA-Z$_][a-zA-Z$_0-9]*$/.test(key) ) < return key; > return JSON.stringify(key); >
'use strict'/* w w w . d e m o 2 s . c o m*/ var rcu = require('rcu'); var Ractive = require('ractive'); var CleanCSS = require('clean-css'); var toSource = require('tosource'); rcu.init(Ractive); module.exports = function (source) < this.cacheable(); var fileName = this.request ? this.request.replace(/^.*[\\\/]/, '') : '' var isPartial = fileName.startsWith('_') var definition = rcu.parse(source); var templateSource = toSource(definition.template, null, '') if (isPartial) < return 'module.exports = ' + templateSource + ';\n' > return '' + "var Ractive = require('ractive');\n" + 'var component = module;\n' + ( definition.script ? definition.script + '\n' : '' ) + 'component.exports.template = ' + templateSource + ';\n' + ( definition.css ? 'component.exports.css = ' + JSON.stringify(new CleanCSS().minify(definition.css).styles) + ';\n' : '' ) + ( definition.imports.length ? 'component.exports.components = + definition.imports.map(getImportKeyValuePair).join(', ') + '>;\n' : '' ) + 'module.exports = Ractive.extend(component.exports);\n'; >; function getImportKeyValuePair(imported, i) < return stringify(imported.name) + ": require('" + imported.href + "')"; > function stringify(key) < if (/^[a-zA-Z$_][a-zA-Z$_0-9]*$/.test(key)) < return key; > return JSON.stringify(key); >
import CleanCSS from 'clean-css'; import toSource from 'tosource'; export default function createOutro ( definition, indent = '' ) < const css = definition.css ? new CleanCSS().minify( definition.css ).styles : ''; const imports = definition.imports.map( getImportKeyValuePair ); let outro = [/* w w w . d e m o 2 s .c o m */ `$component.exports.template = $'' )>;` ]; if ( css ) outro.push( `$component.exports.css = $ ;` ); if ( imports.length ) outro.push( `$component.exports.components = < $ ', ')>>;` ); return outro.join( '\n' ); > function getImportKeyValuePair ( imported, i ) < return `$ name)>: __import$__`; > function stringify ( key ) < if ( /^[a-zA-Z$_][a-zA-Z$_0-9]*$/.test( key ) ) < return key; > return JSON.stringify( key ); >
Related
- Node.js fuzzyjs fuzzyjs is a fuzzy search algorithm in javascript.
- Node.js posthtml-attrs-sorter To follow the guidelines for writing code such as Code Guide by @mdo.
- Node.js fuzzy.js Fuzzy.js is a library for approximate (fuzzy) string matching.
- Node.js tosource toSource is a super simple function that converts JavaScript objects back to source code.
- Node.js restricted-input Allow restricted character sets in input elements.
- Node.js flat Take a nested Javascript object and flatten it, or unflatten an object with delimited keys.
- Node.js split-sms An SMS message splitter with support for both GSM and Unicode written in JavaScript.
demo2s.com | Email: | Demo Source and Support. All rights reserved.
Object.prototype.toSource()
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The toSource() method returns a string representing the source code of the object.
Syntax
Return value
A string representing the source code of the object.
Description
The toSource() method returns the following values:
- For the built-in Object object, toSource() returns the following string indicating that the source code is not available:
function Object() [native code] >
You can call toSource() while debugging to examine the contents of an object.
Overriding the toSource() method
It is safe for objects to override the toSource() method. For example:
function Person(name) this.name = name; > Person.prototype.toSource = function Person_toSource() return 'new Person(' + uneval(this.name) + ')'; >; console.log(new Person('Joe').toSource()); // ---> new Person("Joe")
Built-in toSource() methods
Each core JavaScript type has its own toSource() method. These objects are:
- Array.prototype.toSource() — Array object.
- Boolean.prototype.toSource() — Boolean object.
- Date.prototype.toSource() — Date object.
- Function.prototype.toSource() — Function object.
- Number.prototype.toSource() — Number object.
- RegExp.prototype.toSource() — RegExp object.
- String.prototype.toSource() — String object.
- Symbol.prototype.toSource() — Symbol object.
- Math.toSource() — Returns the String «Math».
Limitations on cyclical objects
In the case of objects that contain references to themselves, e.g. a cyclically linked list or a tree that can be traversed both ways, toSource() will not recreate the self-reference, as of Firefox 24. For example:
var obj1 = >; var obj2 = a: obj1 >; obj1.b = obj2; console.log('Cyclical: ' + (obj1.b.a == obj1)); var objSource = obj1.toSource(); // returns "(>>)" obj1 = eval(objSource); console.log('Cyclical: ' + (obj1.b.a == obj1));
If a cyclical structure is employed and toSource() is needed, the object must provide an override to toSource() , either using a reference to a constructor or providing an anonymous function.
Examples
Using toSource()
The following code defines the Dog object type and creates theDog , an object of type Dog :
function Dog(name, breed, color, sex) this.name = name; this.breed = breed; this.color = color; this.sex = sex; > theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female');
Calling the toSource() method of theDog displays the JavaScript source that defines the object:
Specifications
Browser compatibility
Starting in Firefox 74, toSource() is no longer available for use by web content. It is still allowed for internal and privileged code.