Projekt

Obecné

Profil

Stáhnout (5.61 KB) Statistiky
| Větev: | Revize:
1
Serialize JavaScript
2
====================
3

    
4
Serialize JavaScript to a _superset_ of JSON that includes regular expressions, dates and functions.
5

    
6
[![npm Version][npm-badge]][npm]
7
[![Dependency Status][david-badge]][david]
8
[![Build Status][travis-badge]][travis]
9

    
10
## Overview
11

    
12
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.
13

    
14
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.
15

    
16
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.
17

    
18
> **HTML characters and JavaScript line terminators are escaped automatically.**
19

    
20
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.
21

    
22
## Installation
23

    
24
Install using npm:
25

    
26
```shell
27
$ npm install serialize-javascript
28
```
29

    
30
## Usage
31

    
32
```js
33
var serialize = require('serialize-javascript');
34

    
35
serialize({
36
    str  : 'string',
37
    num  : 0,
38
    obj  : {foo: 'foo'},
39
    arr  : [1, 2, 3],
40
    bool : true,
41
    nil  : null,
42
    undef: undefined,
43
    date: new Date("Thu, 28 Apr 2016 22:02:17 GMT"),
44
    map: new Map([['hello', 'world']]),
45
    set: new Set([123, 456]),
46

    
47
    fn: function echo(arg) { return arg; },
48
    re: /([^\s]+)/g
49
});
50
```
51

    
52
The above will produce the following string output:
53

    
54
```js
55
'{"str":"string","num":0,"obj":{"foo":"foo"},"arr":[1,2,3],"bool":true,"nil":null,"undef":undefined,"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":/([^\s]+)/g}'
56
```
57

    
58
Note: to produced a beautified string, you can pass an optional second argument to `serialize()` to define the number of spaces to be used for the indentation.
59

    
60
### Automatic Escaping of HTML Characters
61

    
62
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.
63

    
64
```js
65
serialize({
66
    haxorXSS: '</script>'
67
});
68
```
69

    
70
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 to terminate:
71

    
72
```js
73
'{"haxorXSS":"\\u003C\\u002Fscript\\u003E"}'
74
```
75

    
76
> You can pass an optional `unsafe` argument to `serialize()` for straight serialization.
77

    
78
### Options
79

    
80
The `serialize()` function accepts an `options` object as its second argument. All options are being defaulted to `undefined`:
81

    
82
#### `options.space`
83

    
84
This option is the same as the `space` argument that can be passed to [`JSON.stringify`][JSON.stringify]. It can be used to add whitespace and indentation to the serialized output to make it more readable.
85

    
86
```js
87
serialize(obj, {space: 2});
88
```
89

    
90
#### `options.isJSON`
91

    
92
This option is a signal to `serialize()` that the object being serialized does not contain any function or regexps values. This enables a hot-path that allows serialization to be over 3x faster. If you're serializing a lot of data, and know its pure JSON, then you can enable this option for a speed-up.
93

    
94
**Note:** That when using this option, the output will still be escaped to protect against XSS.
95

    
96
```js
97
serialize(obj, {isJSON: true});
98
```
99

    
100
#### `options.unsafe`
101

    
102
This option is to signal `serialize()` that we want to do a straight conversion, without the XSS protection. This options needs to be explicitly set to `true`. HTML characters and JavaScript line terminators will not be escaped. You will have to roll your own.
103

    
104
```js
105
serialize(obj, {unsafe: true});
106
```
107

    
108
#### `options.ignoreFunction`
109

    
110
This option is to signal `serialize()` that we do not want serialize JavaScript function. 
111
Just treat function like `JSON.stringify` do, but other features will work as expected.
112

    
113
```js
114
serialize(obj, {ignoreFunction: true});
115
```
116

    
117
## Deserializing
118

    
119
For some use cases you might also need to deserialize the string. This is explicitly not part of this module. However, you can easily write it yourself:
120

    
121
```js
122
function deserialize(serializedJavascript){
123
  return eval('(' + serializedJavascript + ')');
124
}
125
```
126

    
127
**Note:** Don't forget the parentheses around the serialized javascript, as the opening bracket `{` will be considered to be the start of a body.
128

    
129
## License
130

    
131
This software is free to use under the Yahoo! Inc. BSD license.
132
See the [LICENSE file][LICENSE] for license text and copyright information.
133

    
134

    
135
[npm]: https://www.npmjs.org/package/serialize-javascript
136
[npm-badge]: https://img.shields.io/npm/v/serialize-javascript.svg?style=flat-square
137
[david]: https://david-dm.org/yahoo/serialize-javascript
138
[david-badge]: https://img.shields.io/david/yahoo/serialize-javascript.svg?style=flat-square
139
[travis]: https://travis-ci.org/yahoo/serialize-javascript
140
[travis-badge]: https://img.shields.io/travis/yahoo/serialize-javascript.svg?style=flat-square
141
[express-state]: https://github.com/yahoo/express-state
142
[JSON.stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
143
[LICENSE]: https://github.com/yahoo/serialize-javascript/blob/master/LICENSE
(2-2/4)