|
||
---|---|---|
.. | ||
index.js | ||
LICENSE | ||
package.json | ||
README.md |
Serialize JavaScript
Serialize JavaScript to a superset of JSON that includes regular expressions, dates and functions.
[![npm Version][npm-badge]][npm]
[![Dependency Status][david-badge]][david]
Overview
The code in this package began its life as an internal module to [express-state][]. To expand its usefulness, it now lives as serialize-javascript
— an independent package on npm.
You're probably wondering: What about JSON.stringify()
!? We've found that sometimes we need to serialize JavaScript functions, regexps, dates, sets or maps. A great example is a web app that uses client-side URL routing where the route definitions are regexps that need to be shared from the server to the client. But this module is also great for communicating between node processes.
The string returned from this package's single export function is literal JavaScript which can be saved to a .js
file, or be embedded into an HTML document by making the content of a <script>
element.
HTML characters and JavaScript line terminators are escaped automatically.
Please note that serialization for ES6 Sets & Maps requires support for Array.from
(not available in IE or Node < 0.12), or an Array.from
polyfill.
Installation
Install using npm:
$ npm install serialize-javascript
Usage
var serialize = require('serialize-javascript');
serialize({
str : 'string',
num : 0,
obj : {foo: 'foo'},
arr : [1, 2, 3],
bool : true,
nil : null,
undef: undefined,
inf : Infinity,
date : new Date("Thu, 28 Apr 2016 22:02:17 GMT"),
map : new Map([['hello', 'world']]),
set : new Set([123, 456]),
fn : function echo(arg) { return arg; },
re : /([^\s]+)/g,
big : BigInt(10),
url : new URL('https://example.com/'),
});
The above will produce the following string output:
'{"str":"string","num":0,"obj":{"foo":"foo"},"arr":[1,2,3],"bool":true,"nil":null,"undef":undefined,"inf":Infinity,"date":new Date("2016-04-28T22:02:17.000Z"),"map":new Map([["hello","world"]]),"set":new Set([123,456]),"fn":function echo(arg) { return arg; },"re":new RegExp("([^\\\\s]+)", "g"),"big":BigInt("10"),"url":new URL("https://example.com/")}'
Note: to produce a beautified string, you can pass an optional second argument to serialize()
to define the number of spaces to be used for the indentation.
Automatic Escaping of HTML Characters
A primary feature of this package is to serialize code to a string of literal JavaScript which can be embedded in an HTML document by adding it as the contents of the <script>
element. In order to make this safe, HTML characters and JavaScript line terminators are escaped automatically.
serialize({
haxorXSS: '</script>'
});
The above will produce the following string, HTML-escaped output which is safe to put into an HTML document as it will not cause the inline script element