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

nodejs交互工具庫系列

做用
chalk-pipe 使用更簡單的樣式字符串建立粉筆樣式方案
chalk 正確處理終端字符串樣式
Commander.js 完整的 node.js 命令行解決方案
Inquirer.js 一組通用的交互式命令行用戶界面。
slash 系統路徑符處理
minimist 解析參數選項
dotenv 將環境變量從 .env文件加載到process.env中
dotenv-expand 擴展計算機上已經存在的環境變量
hash-sum 很是快的惟一哈希生成器
deepmerge 深度合併兩個或多個對象的可枚舉屬性。
yaml-front-matter 解析yaml或json
resolve 實現node的 require.resolve()算法,這樣就能夠異步和同步地使用require.resolve()表明文件
semver npm的語義版本器
leven 測量兩字符串之間的差別<br/>最快的JS實現之一
lru cache 刪除最近最少使用的項的緩存對象
portfinder 自動尋找 800065535內可用端口號
ora 優雅的終端轉輪
envinfo 生成故障排除軟件問題(如操做系統、二進制版本、瀏覽器、已安裝語言等)時所需的通用詳細信息的報告
memfs 內存文件系統與Node's fs API相同實現
execa 針對人類的流程執行
webpack-merge 用於鏈接數組和合並對象,從而建立一個新對象
webpack-chain 使用鏈式API去生成簡化webpack版本配置的修改
strip-ansi 從字符串中去掉ANSI轉義碼
address 獲取當前機器的IP, MAC和DNS服務器。
default-gateway 經過對OS路由接口的exec調用得到機器的默認網關
joi JavaScript最強大的模式描述語言和數據驗證器。
fs-extra 添加了未包含在原生fs模塊中的文件系統方法,並向fs方法添加了promise支持
Acorn 一個小而快速的JavaScript解析器,徹底用JavaScript編寫。
zlib.js ZLIB.js是ZLIB(RFC1950), DEFLATE(RFC1951), GZIP(RFC1952)和PKZIP在JavaScript實現。

nodejs交互工具庫 -- chalk-pipe和chalk前端

nodejs交互工具庫 -- commander和Inquirernode

nodejs交互工具庫 -- slash, minimist和dotenv, dotenv-expandwebpack

nodejs交互工具庫 -- hash-sum, deepmerge和yaml-front-mattergit

nodejs交互工具庫 -- resolve和semvergithub

nodejs交互工具庫 -- leven, lru cache和portfinderweb

nodejs交互工具庫 -- ora和envinfo算法

nodejs交互工具庫 -- memfs和execanpm

nodejs交互工具庫 -- webpack-merge和webpack-chainjson

nodejs交互工具庫 -- strip-ansi, address, default-gateway和joisegmentfault

nodejs交互工具庫 -- fs-extra, Acorn和zlib

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

相關文章
相關標籤/搜索