实现效果
目录
- 简介
- 安装
- 示例
- 1、json比较diffJson
- 2、按行比较diffLines
- 3、比较数组diffArrays
- 总结
- 参考资料
简介
A javascript text differencing implementation.
译文:javascript文本差异实现。
相关文档
- github https://github.com/kpdecker/jsdiff
- npmjs https://www.npmjs.com/package/diff
安装
npm
npm install diff --save
CDN:
https://unpkg.com/diff@5.1.0/dist/diff.js
示例
1、json比较diffJson
// CommonJS
// const Diff = require('diff')
// EMS
import * as Diff from 'diff'
const one = {
id: 1,
name: 'Tom',
age: 18,
}
const other = {
id: 2,
name: 'Jack',
age: 18,
}
const diff = Diff.diffJson(one, other)
console.log(diff);
输出
[
{ count: 2, value: '{\n "age": 18,\n' },
{
count: 2,
added: undefined,
removed: true,
value: ' "id": 1,\n "name": "Tom"\n'
},
{
count: 2,
added: true,
removed: undefined,
value: ' "id": 2,\n "name": "Jack"\n'
},
{ count: 1, value: '}' }
]
2、按行比较diffLines
// const Diff = require('diff')
import * as Diff from 'diff'
const one = {
id: 1,
name: 'Tom',
age: 18,
}
const other = {
id: 2,
name: 'Jack',
age: 18,
}
const diff = Diff.diffLines(
JSON.stringify(one, null, 2),
JSON.stringify(other, null, 2)
)
console.log(diff)
输出
[
{ count: 1, value: '{\n' },
{
count: 2,
added: undefined,
removed: true,
value: ' "id": 1,\n "name": "Tom",\n'
},
{
count: 2,
added: true,
removed: undefined,
value: ' "id": 2,\n "name": "Jack",\n'
},
{ count: 2, value: ' "age": 18\n}' }
]
3、比较数组diffArrays
// const Diff = require('diff')
import * as Diff from 'diff'
const one = {
id: 1,
name: 'Tom',
age: 18,
}
const other = {
id: 2,
name: 'Jack',
age: 18,
}
const diff = Diff.diffArrays(
JSON.stringify(one, null, 2).split('\n'),
JSON.stringify(other, null, 2).split('\n'),
)
console.log(diff);
// 组装结果
let list = diff.map((part) => {
if (part.added) {
return part.value.map(x=>'+' + x).join('\n')
} else if (part.removed) {
return part.value.map(x=>'-' + x).join('\n')
} else {
return part.value.join('\n')
}
})
console.log(list.join('\n'))
输出
[
{ count: 1, value: [ '{' ] },
{
count: 2,
added: undefined,
removed: true,
value: [ ' "id": 1,', ' "name": "Tom",' ]
},
{
count: 2,
added: true,
removed: undefined,
value: [ ' "id": 2,', ' "name": "Jack",' ]
},
{ count: 2, value: [ ' "age": 18', '}' ] }
]
组合后输出
{
- "id": 1,
- "name": "Tom",
+ "id": 2,
+ "name": "Jack",
"age": 18
}
总结
通过以上示例可以发现:
- json比较的缺点,行的
先后顺序
改变了 - 按行比较的缺点,有很多的 回车符
\n
不好按行处理 - 比较数组较为理想,可以继保留了输入顺序,同时也能够按行处理比较结果
参考资料
- 在线示例
- diff.js使用指南