Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Utilities for Hexo.

License

NotificationsYou must be signed in to change notification settings

hexojs/hexo-util

Repository files navigation

Build StatusNPM versionCoverage Status

Utilities forHexo.

Table of contents

Installation

$ npm install hexo-util --save

Usage

varutil=require('hexo-util');

Cache()

A simple plain object cache

constcache=newCache();// set(key, value)cache.set('foo','bar');// get(key) => valuecache.get('foo');// 'bar'// has(key) => Booleancache.has('foo');// truecache.has('bar');// false// apply(key. value)cache.apply('baz',()=>123);// 123cache.apply('baz',()=>456);// 123cache.apply('qux',456);// 456cache.apply('qux','789');// 456// size()cache.size();// 3// dump()cache.dump();/*{  foo: 'bar',  baz: 123,  qux: 456}*/// del(key)cache.del('baz');cache.has('baz');// false// flush()cache.flush();cache.has('foo');// falsecache.size();// 0

CacheStream()

Caches contents piped to the stream.

varstream=newCacheStream();fs.createReadStream('/path/to/file').pipe(stream);stream.on('finish',function(){// Read cache piped to the streamconsole.log(stream.getCache());// Destroy cachestream.destroy();});

camelCaseKeys(obj, options)

Convert object keys to camelCase. Original keys will be converted to getter/setter and sync to the camelCase keys.

camelCaseKeys({foo_bar:'test'});// { fooBar: 'test', foo_bar: 'test' }

createSha1Hash()

return SHA1 hash object.This is the same as callingcreateHash('utf8') in the node.js native module crypto.

constsha1=createSha1Hash();fs.createReadStream('/path/to/file').pipe(sha1).on('finish',()=>{console.log(sha1.read());});

decodeURL(str)

Decodeencoded URL or path. An alternative to the nativedecodeURI() function, with added ability to decodepunycoded domain.

decodeURL('http://foo.com/b%C3%A1r')// http://foo.com/bárdecodeURL('http://xn--br-mia.com/baz')// http://bár.com/bazdecodeURL('/foo/b%C3%A1r/')// /foo/bár//* Alternatively, Node 10+ offers native API to decode punycoded domain */const{format}=require('url')decodeURI(format(newURL('http://xn--br-mia.com.com/b%C3%A1r'),{unicode:true}))// http://bár.com/báz

deepMerge(target, source)

Merges the enumerable properties of two objects deeply.target andsource remain untouched.

// Merge deeplyconstobj1={a:{b:1,c:1,d:{e:1,f:1}}};constobj2={a:{b:2,d:{f:'f'}}};deepMerge(obj1,obj2);// {a: {b: 2, c: 1, d: {e: 1, f: 'f'}}}
// Arrays will be combined in the same property, similar to lodash.mergeconstobj1={'a':[{'b':2},{'d':4}]};constobj2={'a':[{'c':3},{'e':5}]};deepMerge(obj1,obj2);// { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }]};

encodeURL(str)

Encode URL or path into asafe format.

encodeURL('http://foo.com/bár')// http://foo.com/b%C3%A1rencodeURL('/foo/bár/')// /foo/b%C3%A1r/

escapeDiacritic(str)

Escapes diacritic characters in a string.

escapeHTML(str)

Escapes HTML entities in a string.

escapeHTML('<p>Hello "world".</p>')// &lt;p&gt;Hello &quot;world&quot;.&lt;&#x2F;p&gt;/* support escaped characters */escapeHTML('&lt;foo>bar</foo&gt;')// &lt;foo&gt;bar&lt;&#x2F;foo&gt;

escapeRegex(str)

Escapes special characters in a regular expression.

full_url_for(path)

Returns a url with the config.url prefixed. Output isencoded automatically. Requiresbind(hexo).

_config.ymlurl:https://example.com/blog# example
full_url_for('/a/path')// https://example.com/blog/a/path

gravatar(str, [options])

Returns the gravatar image url from an email.

If 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.

OptionDescriptionDefault
sOutput image size80
dDefault image
fForce default
rRating

More info:Gravatar

gravatar('a@abc.com')// https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787gravatar('a@abc.com',40)// https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787?s=40gravatar('a@abc.com'{s:40,d:'https://via.placeholder.com/150'})// https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787?s=40&d=https%3A%2F%2Fvia.placeholder.com%2F150

hash(str)

Generates SHA1 hash.

hash('123456');// <Buffer 7c 4a 8d 09 ca 37 62 af 61 e5 95 20 94 3d c2 64 94 f8 94 1b>

highlight(str, [options])

Syntax highlighting for a code block.

OptionDescriptionDefault
gutterWhether to show line numberstrue
wrapWhether to wrap the code block in<table>true
firstLineFirst line number1
hljsWhether to use thehljs-* prefix for CSS classesfalse
langLanguage
captionCaption
tabReplace tabs
autoDetectDetect language automatically (warning: slow)
Sublanguage highlight requiresautoDetect to be enabled andlang to be unset
false
markLine highlight specific line(s)
languageAttrOutput code language intodata-language attrfalse
stripIndentWhether to strip leading whitespace viastrip-indenttrue

htmlTag(tag, attrs, text, escape)

Creates a html tag.

OptionDescriptionDefault
tagTag / element name
attrsAttribute(s) and its value.
Value is alwaysescaped, URL is alwaysencoded.
textText, the value is always escaped
(except for<style> tag)
escapeWhether to escape the texttrue
htmlTag('img',{src:'example.png'})// <img src="example.png">htmlTag('a',{href:'http://hexo.io/'},'Hexo')// <a href="http://hexo.io/">Hexo</a>htmlTag('link',{href:'http://foo.com/'},'<a>bar</a>')// <a href="http://foo.com/">&lt;bar&gt;</a>htmlTag('a',{href:'http://foo.com/'},'<b>bold</b>',false)// <a href="http://foo.com/"><b>bold</b></a>/* text value of <style> won't be escaped, url is still encoded */htmlTag('style',{},'p { content: "<"; background: url("bár.jpg"); }')// <style>p { content: "<"; background: url("b%C3%A1r.jpg"); }</style>/* support script tag with async/defer */htmlTag('script',{src:'/foo.js',async:true},'')// <script src="/foo.js" async></script>

isExternalLink(url, sitehost, [exclude])

OptionDescriptionDefault
urlThe input URL.
sitehostThe hostname / url of website. You can also passhexo.config.url.
excludeExclude hostnames. Specific subdomain is required when applicable, includingwww.[]

Returns if a given url is external link relative to givensitehost and[exclude].

// 'sitehost' can be a domain or urlisExternalLink('https://example.com','example.com');// falseisExternalLink('https://example.com','https://example.com');// falseisExternalLink('https://example.com','//example.com/blog/');// false
isExternalLink('/archives/foo.html','example.com');// falseisExternalLink('https://foo.com/','example.com');// true
isExternalLink('https://foo.com','example.com',['foo.com','bar.com']);// falseisExternalLink('https://bar.com','example.com',['foo.com','bar.com']);// falseisExternalLink('https://baz.com/','example.com',['foo.com','bar.com']);// true

Pattern(rule)

Parses the string and tests if the string matches the rule.rule can be a string, a regular expression or a function.

varpattern=newPattern('posts/:id');pattern.match('posts/89');// {0: 'posts/89', 1: '89', id: '89'}
varpattern=newPattern('posts/*path');pattern.match('posts/2013/hello-world');// {0: 'posts/2013/hello-world', 1: '2013/hello-world', path: '2013/hello-world'}

Permalink(rule, [options])

Parses a permalink.

OptionDescription
segmentsCustomize the rule of a segment in the permalink
varpermalink=newPermalink(':year/:month/:day/:title',{segments:{year:/(\d{4})/,month:/(\d{2})/,day:/(\d{2})/}});permalink.parse('2014/01/31/test');// {year: '2014', month: '01', day: '31', title: 'test'}permalink.test('2014/01/31/test');// truepermalink.stringify({year:'2014',month:'01',day:'31',title:'test'})// 2014/01/31/test

prettyUrls(url, [options])

Rewrite urls to pretty URLs.

OptionDescriptionDefault
trailing_index/about/index.html -> /about/ whenfalsetrue
trailing_html/about.html -> /about whenfalsetrue

Note:trailing_html ignores any link with a trailingindex.html. (will not be rewritten toindex).

prettyUrls('/foo/bar.html');// /foo/bar.htmlprettyUrls('/foo/bar/index.html');// /foo/bar/index.htmlprettyUrls('/foo/bar.html',{trailing_index:false});// /foo/bar.htmlprettyUrls('/foo/bar/index.html',{trailing_index:false});// /foo/bar/prettyUrls('/foo/bar.html',{trailing_html:false});// /foo/barprettyUrls('/foo/bar/index.html',{trailing_html:false});// /foo/bar/index.htmlprettyUrls('/foo/bar.html',{trailing_index:false,trailing_html:false});// /foo/barprettyUrls('/foo/bar/index.html',{trailing_index:false,trailing_html:false});// /foo/bar/

prismHighlight(str, [options])

Syntax highlighting for a code block using PrismJS.

OptionDescriptionDefault
lineNumberWhether to show line numberstrue
langLanguage'none'
tabReplace tabs
isPreprocessEnable preprocess or nottrue
markHighlight specific line
firstLineFirst line number
captionCaption
stripIndentWhether to strip leading whitespace viastrip-indenttrue

WhenisPreprocess is enabled,prismHighlight() will return PrismJS processed HTML snippet. Otherwisestr will only be escaped andprismHighlight() will return the HTML snippet that is suitable forprism.js working in the Browser.

mark andfirstLine options will have effect only whenisPreprocess is disabled.

relative_url(from, to)

Returns the relative URL fromfrom toto. Output isencoded automatically. Requiresbind(hexo).

relative_url('foo/bar/','css/style.css')// ../../css/style.css

slugize(str, [options])

Transforms a string into a clean URL-friendly string.

OptionDescriptionDefault
separatorSeparator-
transformTransform the string into lower case (1) or upper case (2)
slugize('Hello World')='Hello-World'slugize('Hellô Wòrld')='Hello-World'slugize('Hello World',{separator:'_'})='Hello_World'slugize('Hello World',{transform:1})='hello-world'slugize('Hello World',{transform:2})='HELLO-WORLD'

spawn(command, [args], [options])

Launches a new process with the givencommand. This method returns a promise.

OptionDescriptionDefault
cwdCurrent working directory of the child process
envEnvironment key-value pairs
stdioChild's stdio configurationpipe
detachedThe child will be a process group leader
uidSets the user identity of the process
gidSets the group identity of the process
verboseDisplay messages on the consolefalse
encodingSets the encoding of the output stringutf8

More info:child_process.spawn()

spawn('cat','test.txt').then((content)=>{console.log(content);});// $ cd "/target/folder"// $ cat "foo.txt" "bar.txt"spawn('cat',['foo.txt','bar.txt'],{cwd:'/target/folder'}).then((content)=>{console.log(content);});

stripHTML(str)

Removes HTML tags in a string.

stripIndent(str)

Strip leading whitespace from each line in a string. The line with the least number of leading whitespace, ignoring empty lines, determines the number to remove. Useful for removing redundant indentation.

wordWrap(str, [options])

Wraps the string no longer than line width. This method breaks on the first whitespace character that does not exceed line width.

OptionDescriptionDefault
widthLine width80
wordWrap('Once upon a time')// Once upon a timewordWrap('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...')// 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...wordWrap('Once upon a time',{width:8})// Once\nupon a\ntimewordWrap('Once upon a time',{width:1})// Once\nupon\na\ntime

tocObj(str, [options])

Generate a table of contents in JSON format based on the given html string. Headings with attributedata-toc-unnumbered="true" will be marked as unnumbered.

OptionDescriptionDefault
min_depthThe minimum level of TOC1
max_depthThe maximum level of TOC6
consthtml=['<h1>Title 1</h1>','<div><h2>Title 1.1</h2></div>','<h3>Title 1.1.1</h3>','<h2>Title 1.2</h2>','<h2>Title 1.3</h2>','<h3>Title 1.3.1</h3>','<h1>Title 2</h1>','<h2>Title 2.1</h2>'].join('\n');tocObj(html);/*[  { text: 'Title 1', id: 'title_1', level: 1 },  { text: 'Title 1.1', id: 'title_1_1', level: 2 },  { text: 'Title 1.1.1', id: 'title_1_1_1', level: 3 },  { text: 'Title 1.2', id: 'title_1_2', level: 2 },  { text: 'Title 1.3', id: 'title_1_3', level: 2 },  { text: 'Title 1.3.1', id: 'title_1_3_1', level: 3 },  { text: 'Title 2', id: 'title_2', level: 1 },  { text: 'Title 2.1', id: 'title_2_1', level: 2 },]*/tocObj(html,{min_depth:2});/*[  { text: 'Title 1.1', id: 'title_1_1', level: 2 },  { text: 'Title 1.1.1', id: 'title_1_1_1', level: 3 },  { text: 'Title 1.2', id: 'title_1_2', level: 2 },  { text: 'Title 1.3', id: 'title_1_3', level: 2 },  { text: 'Title 1.3.1', id: 'title_1_3_1', level: 3 },  { text: 'Title 2.1', id: 'title_2_1', level: 2 },]*/tocObj(html,{max_depth:2});/*[  { text: 'Title 1', id: 'title_1', level: 1 },  { text: 'Title 1.1', id: 'title_1_1', level: 2 },  { text: 'Title 1.2', id: 'title_1_2', level: 2 },  { text: 'Title 1.3', id: 'title_1_3', level: 2 },  { text: 'Title 2', id: 'title_2', level: 1 },  { text: 'Title 2.1', id: 'title_2_1', level: 2 },]*/tocObj('<h1 data-toc-unnumbered="true">Reference</h1>')/*[  { text: 'Reference', id: 'reference', level: 1, unnumbered: true }]*/

truncate(str, [options])

Truncates a given text after a givenlength if text is longer thanlength. The last characters will be replaced with theomission option for a total length not exceedinglength.

OptionDescriptionDefault
lengthMax length of the string30
omissionOmission text...
separatortruncate text at a natural break
truncate('Once upon a time in a world far far away')// "Once upon a time in a world..."truncate('Once upon a time in a world far far away',{length:17})// "Once upon a ti..."truncate('Once upon a time in a world far far away',{length:17,separator:' '})// "Once upon a..."truncate('And they found that many people were sleeping better.',{length:25,omission:'... (continued)'})// "And they f... (continued)"

unescapeHTML(str)

Unescapes HTML entities in a string.

unescapeHTML('&lt;p&gt;Hello &quot;world&quot;.&lt;&#x2F;p&gt;')// <p>Hello "world".</p>

url_for(path, [option])

Returns a url with the root path prefixed. Output isencoded automatically. Requiresbind(hexo).

OptionDescriptionDefault
relativeOutput relative linkValue ofconfig.relative_link
_config.ymlroot:/blog/# example
url_for('/a/path')// /blog/a/path

Relative link, followsrelative_link option by defaulte.g. post/page path is '/foo/bar/index.html'

_config.ymlrelative_link:true
url_for('/css/style.css')// ../../css/style.css/* Override option * you could also disable it to output a non-relative link, * even when `relative_link` is enabled and vice versa. */url_for('/css/style.css',{relative:false})// /css/style.css

bind(hexo)

Following utilities requirebind(hexo) /bind(this) /call(hexo, input) /call(this, input) to parse the user config when initializing:

Below examples demonstrate different approaches to creating ahelper (each example is separated by/******/),

// Single functionconsturl_for=require('hexo-util').url_for.bind(hexo);hexo.extend.helper.register('test_url',(str)=>{returnurl_for(str);})/******/// Multiple functionsconsturl_for=require('hexo-util').url_for.bind(hexo)functiontesturlHelper(str){returnurl_for(str);}hexo.extend.helper.register('test_url',testurlHelper);/******/// Functions separated into different files.// test_url.jsmodule.exports=function(str){consturl_for=require('hexo-util').url_for.bind(this);returnurl_for(str);}// index.jshexo.extend.helper.register('test_url',require('./test_url'));/******/// Function.call() approach also worksconst{url_for}=require('hexo-util');module.exports=function(str){returnurl_for.call(this,str);}hexo.extend.helper.register('test_url',require('./test_url'));/******/// Separating functions into individual files// Each file has multiple functions// test_url.jsfunctiontesturlHelper(str){consturl_for=require('hexo-util').url_for.bind(this);returnurl_for(str);}module.exports={testurlHelper:testurlHelper}// index.jshexo.extend.helper.register('test_url',require('./test_url').testurlHelper);

License

MIT

About

Utilities for Hexo.

Topics

Resources

License

Security policy

Stars

Watchers

Forks

Sponsor this project

    Packages

    No packages published

    Contributors33


    [8]ページ先頭

    ©2009-2025 Movatter.jp