UNPKG

12.8 kBMarkdownView Raw
1# hexo-util
2
3[![Build Status](https://travis-ci.com/hexojs/hexo-util.svg?branch=master)](https://travis-ci.com/hexojs/hexo-util)
4[![NPM version](https://badge.fury.io/js/hexo-util.svg)](https://www.npmjs.com/package/hexo-util)
5[![Coverage Status](https://coveralls.io/repos/hexojs/hexo-util/badge.svg?branch=master&service=github)](https://coveralls.io/github/hexojs/hexo-util?branch=master)
6[![dependencies Status](https://david-dm.org/hexojs/hexo-util/status.svg)](https://david-dm.org/hexojs/hexo-util)
7[![devDependencies Status](https://david-dm.org/hexojs/hexo-util/dev-status.svg)](https://david-dm.org/hexojs/hexo-util?type=dev)
8
9Utilities for [Hexo].
10
11## Installation
12
13``` bash
14$ npm install hexo-util --save
15```
16
17## Usage
18
19``` js
20var util = require('hexo-util');
21```
22
23### CacheStream()
24
25Caches contents piped to the stream.
26
27``` js
28var stream = new CacheStream();
29
30fs.createReadStream('/path/to/file').pipe(stream);
31
32stream.on('finish', function(){
33 // Read cache piped to the stream
34 console.log(stream.getCache());
35
36 // Destroy cache
37 stream.destroy();
38});
39```
40
41### camelCaseKeys(obj, options)
42
43Convert object keys to camelCase. Original keys will be converted to getter/setter and sync to the camelCase keys.
44
45``` js
46camelCaseKeys({
47 foo_bar: 'test'
48});
49// { fooBar: 'test', foo_bar: 'test' }
50```
51
52### createSha1Hash()
53return SHA1 hash object.
54 This is the same as calling `createHash('utf8')` in the node.js native module crypto.
55 ``` js
56const sha1 = createSha1Hash();
57 fs.createReadStream('/path/to/file')
58 .pipe(sha1)
59 .on('finish', () => {
60 console.log(sha1.read());
61 });
62```
63
64### decodeURL(str)
65
66Decode [encoded](https://en.wikipedia.org/wiki/Percent-encoding) URL or path. An alternative to the native [`decodeURI()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) function, with added ability to decode [punycoded](https://en.wikipedia.org/wiki/Punycode) domain.
67
68``` js
69decodeURL('http://foo.com/b%C3%A1r')
70// http://foo.com/bár
71
72decodeURL('http://xn--br-mia.com/baz')
73// http://bár.com/baz
74
75decodeURL('/foo/b%C3%A1r/')
76// /foo/bár/
77```
78
79### encodeURL(str)
80
81Encode URL or path into a [safe format](https://en.wikipedia.org/wiki/Percent-encoding). Domain is encoded into [punycode](https://en.wikipedia.org/wiki/Punycode) when necessary.
82
83``` js
84encodeURL('http://foo.com/bár')
85// http://foo.com/b%C3%A1r
86
87encodeURL('http://bár.com/baz')
88// http://xn--br-mia.com/baz
89
90encodeURL('/foo/bár/')
91// /foo/b%C3%A1r/
92```
93
94### escapeDiacritic(str)
95
96Escapes diacritic characters in a string.
97
98### escapeHTML(str)
99
100Escapes HTML entities in a string.
101
102``` js
103escapeHTML('<p>Hello "world".</p>')
104// &lt;p&gt;Hello &quot;world&quot;.&lt;&#x2F;p&gt;
105
106/* support escaped characters */
107escapeHTML('&lt;foo>bar</foo&gt;')
108// &lt;foo&gt;bar&lt;&#x2F;foo&gt;
109```
110
111### escapeRegex(str)
112
113Escapes special characters in a regular expression.
114
115### full_url_for(path)
116
117Returns a url with the config.url prefixed. Output is [encoded](#encodeurlstr) automatically. Requires [`bind(hexo)`](#bindhexo).
118
119``` yml
120_config.yml
121url: https://example.com/blog # example
122```
123
124``` js
125full_url_for('/a/path')
126// https://example.com/blog/a/path
127```
128
129### gravatar(str, [options])
130
131Returns the gravatar image url from an email.
132
133If you didn't specify the [options] parameter, the default options will apply. Otherwise, you can set it to a number which will then be passed on as the size parameter to Gravatar. Finally, if you set it to an object, it will be converted into a query string of parameters for Gravatar.
134
135Option | Description | Default
136--- | --- | ---
137`s` | Output image size | 80
138`d` | Default image |
139`f` | Force default |
140`r` | Rating |
141
142More info: [Gravatar](https://en.gravatar.com/site/implement/images/)
143
144``` js
145gravatar('a@abc.com')
146// https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787
147gravatar('a@abc.com', 40)
148// https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787?s=40
149gravatar('a@abc.com' {s: 40, d: 'https://via.placeholder.com/150'})
150// https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787?s=40&d=https%3A%2F%2Fvia.placeholder.com%2F150
151```
152
153### hash(str)
154
155Generates SHA1 hash.
156
157``` js
158hash('123456');
159// <Buffer 7c 4a 8d 09 ca 37 62 af 61 e5 95 20 94 3d c2 64 94 f8 94 1b>
160```
161
162### HashStream()
163**\[deprecated\]** use [`createSha1Hash()`](#createsha1hash).
164
165Generates SHA1 hash with a transform stream.
166
167``` js
168var stream = new HashStream();
169
170fs.createReadStream('/path/to/file')
171 .pipe(stream)
172 .on('finish', function(){
173 console.log(stream.read());
174 });
175```
176
177### highlight(str, [options])
178
179Syntax highlighting for a code block.
180
181Option | Description | Default
182--- | --- | ---
183`gutter` | Whether to show line numbers | true
184`wrap` | Whether to wrap the code block | true
185`firstLine` | First line number | 1
186`hljs` | Whether to use the `hljs-*` prefix for CSS classes | false
187`lang` | Language |
188`caption` | Caption |
189`tab`| Replace tabs |
190`autoDetect` | Detect language automatically | false
191
192### htmlTag(tag, attrs, text, escape)
193
194Creates a html tag.
195
196Option | Description | Default
197--- | --- | ---
198`tag` | Tag / element name |
199`attrs` | Attribute(s) and its value.<br>Value is always [escaped](#escapehtmlstr), URL is always [encoded](#encodeurlstr). |
200`text` | Text, the value is always escaped<br>_(except for `<style>` tag)_ |
201`escape` | Whether to escape the text | true
202
203``` js
204htmlTag('img', {src: 'example.png'})
205// <img src="example.png">
206
207htmlTag('a', {href: 'http://hexo.io/'}, 'Hexo')
208// <a href="http://hexo.io/">Hexo</a>
209
210htmlTag('link', {href: 'http://foo.com/'}, '<a>bar</a>')
211// <a href="http://foo.com/">&lt;bar&gt;</a>
212
213htmlTag('a', {href: 'http://foo.com/'}, '<b>bold</b>', false)
214// <a href="http://foo.com/"><b>bold</b></a>
215
216/* text value of <style> won't be escaped, url is still encoded */
217htmlTag('style', {}, 'p { content: "<"; background: url("bár.jpg"); }')
218// <style>p { content: "<"; background: url("b%C3%A1r.jpg"); }</style>
219
220/* support script tag with async/defer */
221htmlTag('script', {src: '/foo.js', async: true}, '')
222// <script src="/foo.js" async></script>
223```
224
225### Pattern(rule)
226
227Parses the string and tests if the string matches the rule. `rule` can be a string, a regular expression or a function.
228
229``` js
230var pattern = new Pattern('posts/:id');
231
232pattern.match('posts/89');
233// {0: 'posts/89', 1: '89', id: '89'}
234```
235
236``` js
237var pattern = new Pattern('posts/*path');
238
239pattern.match('posts/2013/hello-world');
240// {0: 'posts/2013/hello-world', 1: '2013/hello-world', path: '2013/hello-world'}
241```
242
243### Permalink(rule, [options])
244
245Parses a permalink.
246
247Option | Description
248--- | ---
249`segments` | Customize the rule of a segment in the permalink
250
251``` js
252var permalink = new Permalink(':year/:month/:day/:title', {
253 segments: {
254 year: /(\d{4})/,
255 month: /(\d{2})/,
256 day: /(\d{2})/
257 }
258});
259
260permalink.parse('2014/01/31/test');
261// {year: '2014', month: '01', day: '31', title: 'test'}
262
263permalink.test('2014/01/31/test');
264// true
265
266permalink.stringify({year: '2014', month: '01', day: '31', title: 'test'})
267// 2014/01/31/test
268```
269
270### relative_url(from, to)
271
272Returns the relative URL from `from` to `to`. Output is [encoded](#encodeurlstr) automatically. Requires [`bind(hexo)`](#bindhexo).
273
274``` js
275relative_url('foo/bar/', 'css/style.css')
276// ../../css/style.css
277```
278
279### slugize(str, [options])
280
281Transforms a string into a clean URL-friendly string.
282
283Option | Description | Default
284--- | --- | ---
285`separator` | Separator | -
286`transform` | Transform the string into lower case (`1`) or upper case (`2`) |
287
288``` js
289slugize('Hello World') = 'Hello-World'
290slugize('Hellô Wòrld') = 'Hello-World'
291slugize('Hello World', {separator: '_'}) = 'Hello_World'
292slugize('Hello World', {transform: 1}) = 'hello-world'
293slugize('Hello World', {transform: 2}) = 'HELLO-WORLD'
294```
295
296### spawn(command, [args], [options])
297
298Launches a new process with the given `command`. This method returns a promise.
299
300Option | Description | Default
301--- | --- | ---
302`cwd` | Current working directory of the child process |
303`env` | Environment key-value pairs |
304`stdio` | Child's stdio configuration |
305`detached` | The child will be a process group leader |
306`uid` | Sets the user identity of the process |
307`gid` | Sets the group identity of the process |
308`verbose` | Display messages on the console | `false`
309`encoding` | Sets the encoding of the output string | `utf8`
310
311``` js
312spawn('cat', 'test.txt').then(function(content){
313 console.log(content);
314});
315```
316
317### stripHTML(str)
318
319Removes HTML tags in a string.
320
321### wordWrap(str, [options])
322
323Wraps the string no longer than line width. This method breaks on the first whitespace character that does not exceed line width.
324
325Option | Description | Default
326--- | --- | ---
327`width` | Line width | 80
328
329``` js
330wordWrap('Once upon a time')
331// Once upon a time
332
333wordWrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...')
334// Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\na successor to the throne turned out to be more trouble than anyone could have\nimagined...
335
336wordWrap('Once upon a time', {width: 8})
337// Once\nupon a\ntime
338
339wordWrap('Once upon a time', {width: 1})
340// Once\nupon\na\ntime
341```
342
343### truncate(str, [options])
344
345Truncates a given text after a given `length` if text is longer than `length`. The last characters will be replaced with the `omission` option for a total length not exceeding `length`.
346
347Option | Description | Default
348--- | --- | ---
349`length` | Max length of the string | 30
350`omission` | Omission text | ...
351`separator` | truncate text at a natural break |
352
353``` js
354truncate('Once upon a time in a world far far away')
355// "Once upon a time in a world..."
356
357truncate('Once upon a time in a world far far away', {length: 17})
358// "Once upon a ti..."
359
360truncate('Once upon a time in a world far far away', {length: 17, separator: ' '})
361// "Once upon a..."
362
363truncate('And they found that many people were sleeping better.', {length: 25, omission: '... (continued)'})
364// "And they f... (continued)"
365```
366
367### unescapeHTML(str)
368
369Unescapes HTML entities in a string.
370
371``` js
372unescapeHTML('&lt;p&gt;Hello &quot;world&quot;.&lt;&#x2F;p&gt;')
373// <p>Hello "world".</p>
374```
375
376### url_for(path, [option])
377
378Returns a url with the root path prefixed. Output is [encoded](#encodeurlstr) automatically. Requires [`bind(hexo)`](#bindhexo).
379
380Option | Description | Default
381--- | --- | ---
382`relative` | Output relative link | Value of `config.relative_link`
383
384``` yml
385_config.yml
386root: /blog/ # example
387```
388
389``` js
390url_for('/a/path')
391// /blog/a/path
392```
393
394Relative link, follows `relative_link` option by default
395e.g. post/page path is '/foo/bar/index.html'
396
397``` yml
398_config.yml
399relative_link: true
400```
401
402``` js
403url_for('/css/style.css')
404// ../../css/style.css
405
406/* Override option
407 * you could also disable it to output a non-relative link,
408 * even when `relative_link` is enabled and vice versa.
409 */
410url_for('/css/style.css', {relative: false})
411// /css/style.css
412```
413
414## bind(hexo)
415
416Following utilities require `bind(hexo)` / `bind(this)` / `call(hexo, input)` / `call(this, input)` to parse the user config when initializing:
417- [`full_url_for()`](#full_url_forpath)
418- [`url_for()`](#url_forpath)
419- [`relative_url()`](#relative_urlfrom-to)
420
421Below examples demonstrate different approaches to creating a [helper](https://hexo.io/api/helper) (each example is separated by `/******/`),
422
423``` js
424// Single function
425const url_for = require('hexo-util').url_for.bind(hexo);
426
427hexo.extend.helper.register('test_url', (str) => {
428 return url_for(str);
429})
430
431
432/******/
433// Multiple functions
434const url_for = require('hexo-util').url_for.bind(hexo)
435
436function testurlHelper(str) {
437 return url_for(str);
438}
439
440hexo.extend.helper.register('test_url', testurlHelper);
441
442
443/******/
444// Functions separated into different files.
445// test_url.js
446module.exports = function(str) {
447 const url_for = require('hexo-util').url_for.bind(this);
448 return url_for(str);
449}
450
451// index.js
452hexo.extend.helper.register('test_url', require('./test_url'));
453
454
455/******/
456// Function.call() approach also works
457const {url_for} = require('hexo-util');
458module.exports = function(str) {
459 return url_for.call(this, str);
460}
461
462hexo.extend.helper.register('test_url', require('./test_url'));
463
464
465/******/
466// Separating functions into individual files
467// Each file has multiple functions
468// test_url.js
469function testurlHelper(str) {
470 const url_for = require('hexo-util').url_for.bind(this);
471 return url_for(str);
472}
473
474module.exports = {
475 testurlHelper: testurlHelper
476}
477
478// index.js
479hexo.extend.helper.register('test_url', require('./test_url').testurlHelper);
480```
481
482## License
483
484MIT
485
486[Hexo]: http://hexo.io/