关于javascript:nodejs交互工具库-hashsum-deepmerge和yamlfrontmatter

30次阅读

共计 7931 个字符,预计需要花费 20 分钟才能阅读完成。

nodejs 交互工具库系列

作用
chalk-pipe 应用更简略的款式字符串创立粉笔款式计划
chalk 正确处理终端字符串款式
Commander.js 残缺的 node.js 命令行解决方案
Inquirer.js 一组通用的交互式命令行用户界面。
slash 零碎门路符解决
minimist 解析参数选项
dotenv 将环境变量从 .env 文件加载到 process.env 中
hash-sum 十分快的惟一哈希生成器
deepmerge 深度合并两个或多个对象的可枚举属性。
yaml-front-matter 解析 yaml 或 json

nodejs 交互工具库 — chalk-pipe 和 chalk

nodejs 交互工具库 — commander 和 Inquirer

nodejs 交互工具库 — slash, minimist 和 dotenv

nodejs 交互工具库 — hash-sum, deepmerge 和 yaml-front-matter

hash-sum

十分快的惟一哈希生成器

install

yarn add hash-sum

用法

const sum = require('hash-sum');

console.log(sum([ 0, 1, 2, 3])) // 00a34759
console.log(sum('1988-06-09T03:00:00.000Z')) // dff5ee3c

features

  • 没有依赖关系
  • 最小的占用空间
  • 反对 nodejs, io.js, 浏览器
  • 和浏览器的哈希函数基于它们的源代码
  • 为不同的对象类型产生不同的哈希,
  • 对对象中的循环援用的反对
  • 疏忽了属性调配程序

sum(value)

生成基于的 4 字节 16 进制哈希 value.

# creates unique hashes
00a34759 from: [0, 1, 2, 3]
a8996f0c from: {'0': 0, '1': 1, '2': 2, '3': 3}
5b4c2116 from: {'0': 0, '1': 1, '2': 2, '3': 3, length: 4}
2c937c45 from: {url: 12}
31d55010 from: {headers: 12}
2d2e11bc from: {headers: 122}
ec99d958 from: {headers: '122'}
18c00eee from: {headers: { accept: 'text/plain'} }
6cb332c8 from: {payload: [ 0, 1, 2, 3], headers: [{ a: 'b'} ] }
12ff55db from: {a: [Function: a] }
46f806d2 from: {b: [Function: b] }
0660d9c4 from: {b: [Function: b] }
6c95fc65 from: function () {}
2941766e from: function (a) {}
294f8def from: function (b) {}
2d9c0cb8 from: function (a) {return a;}
ed5c63fc from: function (a) {return a;}
bba68bf6 from: ''2d27667d from:'null'774b96ed from:'false'2d2a1684 from:'true'8daa1a0c from:'0'8daa1a0a from:'1'e38f07cc from:'void 0'6037ea1a from:'undefined'
9b7df12e from: null
3c206f76 from: false
01e34ba8 from: true
8a8f9624 from: Infinity
0315bf8f from: -Infinity
64a48b16 from: NaN
1a96284a from: 0
1a96284b from: 1
29172c1a from: undefined
59322f29 from: {}
095b3a22 from: {a: {}, b: {}}
63be56dd from: {valueOf: [Function: valueOf] }
63be4f5c from: {valueOf: [Function: valueOf] }
5d844489 from: []
ba0bfa14 from: 2019-06-28T21:24:31.215Z
49324d16 from: 2019-06-28T03:00:00.000Z
434c9188 from: 1988-06-09T03:00:00.000Z
ce1b5e44 from: global

参考

根本罕用的办法场景就这些了, 更残缺的用法能够间接查阅文档

hash-sum

deepmerge

深度合并两个或多个对象的可枚举属性。

UMD 包是 723B minified+gzipped

Getting Started

Example Usage

const x = {foo: { bar: 3},
  array: [{
    does: 'work',
    too: [1, 2, 3]
  }]
}

const y = {foo: { baz: 4},
  quux: 5,
  array: [{
    does: 'work',
    too: [4, 5, 6]
  }, {really: 'yes'}]
}

const output = {
  foo: {
    bar: 3,
    baz: 4
  },
  array: [{
    does: 'work',
    too: [1, 2, 3]
  }, {
    does: 'work',
    too: [4, 5, 6]
  }, {really: 'yes'}],
  quux: 5
}

Installation

在 npm 这么做:

npm install deepmerge

deepmerge 能够间接在浏览器中应用,而不须要应用包管理器 / 绑定器: UMD version from unpkg.com.

Include

deepmerge 裸露了一个 CommonJS 入口点:

const merge = require('deepmerge')

ESM 入口点被抛弃因为 Webpack bug.

API

merge(x, y, [options])

深度合并两个对象 x 和 y,返回一个新的合并对象,其中蕴含来自 x 和 y 的元素。

如果 x 和 y 有一个键雷同的元素,那么 y 的值将呈现在后果中。

合并创立一个新对象,因而 x 或 y 都不会被批改。

留神: 默认状况下,数组是通过连贯合并的。

merge.all(arrayOfObjects, [options])

将任意数量的对象合并为单个后果对象。

const foobar = {foo: { bar: 3} }
const foobaz = {foo: { baz: 4} }
const bar = {bar: 'yay!'}

merge.all([foobar, foobaz, bar]) // => {foo: { bar: 3, baz: 4}, bar: 'yay!' }

Options

arrayMerge

有多种办法合并两个数组,上面是一些示例,但您也能够创立本人的自定义函数。

你的 arrayMerge函数将会被调用,有三个参数: 指标数组,源数组和选项对象。

  • isMergeableObject(value)
  • cloneUnlessOtherwiseSpecified(value, options)
arrayMerge 示例: 笼罩指标数组

齐全笼罩现有数组值,而不是连贯它们:

const overwriteMerge = (destinationArray, sourceArray, options) => sourceArray

merge([1, 2, 3],
    [3, 2, 1],
    {arrayMerge: overwriteMerge}
) // => [3, 2, 1]
arrayMerge example: combine arrays

组合两个数组中雷同索引处的对象。

这是默认的数组合并算法 pre-version-2.0.0.

const combineMerge = (target, source, options) => {const destination = target.slice()

    source.forEach((item, index) => {if (typeof destination[index] === 'undefined') {destination[index] = options.cloneUnlessOtherwiseSpecified(item, options)
        } else if (options.isMergeableObject(item)) {destination[index] = merge(target[index], item, options)
        } else if (target.indexOf(item) === -1) {destination.push(item)
        }
    })
    return destination
}

merge([{ a: true}],
    [{b: true}, 'ah yup'],
    {arrayMerge: combineMerge}
) // => [{a: true, b: true}, 'ah yup']

isMergeableObject

默认状况下,deepmerge 克隆简直所有类型对象的所有属性。

如果您的对象是非凡类型的,并且您心愿复制整个对象而不仅仅是复制其属性,那么您可能不心愿这样做。

您能够通过为 isMergeableObject选项传递一个函数来实现这一点。

如果您只想克隆一般对象的属性,而疏忽所有“非凡”类型的实例化对象,那么您可能须要退出 is-plain-object.

const isPlainObject = require('is-plain-object')

function SuperSpecial() {this.special = 'oh yeah man totally'}

const instantiatedSpecialObject = new SuperSpecial()

const target = {
    someProperty: {cool: 'oh for sure'}
}

const source = {someProperty: instantiatedSpecialObject}

const defaultOutput = merge(target, source)

defaultOutput.someProperty.cool // => 'oh for sure'
defaultOutput.someProperty.special // => 'oh yeah man totally'
defaultOutput.someProperty instanceof SuperSpecial // => false

const customMergeOutput = merge(target, source, {isMergeableObject: isPlainObject})

customMergeOutput.someProperty.cool // => undefined
customMergeOutput.someProperty.special // => 'oh yeah man totally'
customMergeOutput.someProperty instanceof SuperSpecial // => true

customMerge

指定一个函数,可用于依据属性名称重写属性的默认合并行为。

customMerge 函数将传递每个属性的键值,并将返回用于合并该属性值的函数。

它也可能返回 undefined,在这种状况下,将应用默认的合并行为。

const alex = {
  name: {
    first: 'Alex',
    last: 'Alexson'
  },
  pets: ['Cat', 'Parrot']
}

const tony = {
  name: {
    first: 'Tony',
    last: 'Tonison'
  },
  pets: ['Dog']
}

const mergeNames = (nameA, nameB) => `${nameA.first} and ${nameB.first}`

const options = {customMerge: (key) => {if (key === 'name') {return mergeNames}
  }
}

const result = merge(alex, tony, options)

result.name // => 'Alex and Tony'
result.pets // => ['Cat', 'Parrot', 'Dog']

clone

Deprecated.

Defaults to true.

如果clonefalse 而后将间接复制子对象,而不是克隆。这是版本 2.x 之前的默认行为。

参考

根本罕用的办法场景就这些了, 更残缺的用法能够间接查阅文档

deepmerge

Yaml Front Matter

在字符串的后面解析 yaml 或 json。将解析后的内容和字符串内容的其余部分放入对象文字中。

Online Demo.

Breaking Changes

这个自述文件是针对 4.x 版本,它引入了破坏性的更改。查看 changelog 获得进一步资讯

3.x readme

Example

This

---
name: Derek Worthen
age: 127
contact:
  email: email@domain.com
  address: some location
pets:
  - cat
  - dog
  - bat
match: !!js/regexp /pattern/gim
run: !!js/function function() {}
---
Some Other content
var fs = require('fs');
var yamlFront = require('yaml-front-matter');

fs.readFile('./some/file.txt', 'utf8', function(fileContents) {console.log(yamlFront.loadFront(fileContents));
});

outputs

{ 
    name: 'Derek Worthen',
    age: 127,
    contact: {email: 'email@domain.com', address: 'some location'},
    pets: ['cat', 'dog', 'bat'],
    match: /pattern/gim,
    run: [Function],
    __content: '\nSome Other Content' 
}

May also use JSON

---
{
    "name": "Derek Worthen",
    "age": "young",
    "anArray": ["one","two"],
    "subObj":{"field1": "one"}
}
---
Some content

NOTE: --- 须要示意前端内容的开始和完结。在开始后必须有一个换行 --- 和完结前的换行符 ---.

Install

npm

$ npm install yaml-front-matter

如果您打算应用命令行工具,请应用 - g 标记。

$ npm install yaml-front-matter -g

带有模块绑定的 node 或客户端(webpack 或 browsify)

var yamlFront = require('yaml-front-matter');

Browser Bundle

dist/yamlFront.js 客户端脚本将把 yaml-front-matter 库公开为全局, yamlFront. 客户端脚本 js-yaml 也是必须的。在某些用例中可能须要加载 espirma。看 js-yaml 获得进一步资讯

<script src="https://unpkg.com/js-yaml@3.10.0/dist/js-yaml.js"></script>
<script src="yamlFront.js"></script>
<script>
  // parse front matter with yamlFront.loadFront(String);
</script>

Note: yaml-front-matter 是作为 umd 包交付的,所以它应该在 commonjs, amd 和浏览器 (作为一个全局) 环境中工作。

Running Browser Example

$ npm install --dev && npm start

而后参观 localhost:8080.

Building from source

将构建文件输入到 dist/.

$ npm install --dev && npm run build

Running Tests

npm install --dev && npm test

Command Line

Usage: yaml-front-matter [options] <yaml-front-matter content>

Options:

-h, --help            output usage information
-v, --version         output the version number
-c, --content [name]  set the property name for the files contents [__content]
--pretty              formats json output with spaces. 

留神,cli 应用 safeLoadFront,因而不会解析蕴含 regexp、函数或未定义值的 yaml。

Example

# Piping content from one file, through yaml parser and into another file
cat ./some/file.txt | yaml-front-matter > output.txt

JS-YAML

Yaml 前端内容包装了 js-yaml 以反对解析 Yaml 前端内容。

API

loadFront(string, [options])

var input = [
        '---\npost: title one\n',
        'anArray:\n - one\n - two\n',
        'subObject:\n prop1: cool\n prop2: two',
        '\nreg: !!js/regexp /pattern/gim',
        '\nfun: !!js/function function() {}\n---\n',
        'content\nmore'
    ].join('');

var results = yamlFront.loadFront(input);
console.log(results);

outputs

{ post: 'title one',
  anArray: ['one', 'two'],
  subObject: {obj1: 'cool', obj2: 'two'},
  reg: /pattern/gim,
  fun: [Function],
  __content: '\ncontent\nmore' }

Front-matter is optional.

yamlFront.loadFront('Hello World');
// => {__content: "Hello World!"}

Content is optional

yamlFront.loadFront('');
// => {__content: ''}

safeLoadFront(string, [options])

api 与 loadFront 雷同,只是它不反对 regexps、函数或 undefined。无关更多信息,请参阅 js-yaml。

Options

options 对象反对与 js-yaml 雷同的选项,并增加了对附加键的反对。

  • options.contentKeyName: 指定用于存储未被 yaml-front-matter 解析的内容的对象键。默认为 __content.
yamlFront.loadFront('Hello World', {contentKeyName: 'fileContents'});
// => {fileContents: "Hello World"}

参考

根本罕用的办法场景就这些了, 更残缺的用法能够间接查阅文档

js-yaml-front-matter

正文完
 0