API Reference

Diff Functions

diffChars(oldStr, newStr, [options])

Compare two strings character by character.

import { diffChars } from 'diff';

const diff = diffChars('hello', 'hallo');
// Returns array of change objects
ParameterTypeDescription
oldStrstringOriginal string
newStrstringNew string to compare
optionsobjectOptional configuration

diffWords(oldStr, newStr, [options])

Compare two strings word by word. Ignores whitespace differences.

import { diffWords } from 'diff';

const diff = diffWords('hello world', 'hello there');

diffLines(oldStr, newStr, [options])

Compare two strings line by line.

import { diffLines } from 'diff';

const diff = diffLines('line1\nline2', 'line1\nline3');

diffJson(oldObj, newObj, [options])

Compare two JSON objects.

import { diffJson } from 'diff';

const diff = diffJson(
  { name: 'John', age: 30 },
  { name: 'John', age: 31 }
);

Patch Functions

createPatch(fileName, oldStr, newStr, oldHeader, newHeader, [options])

Create a unified diff patch.

import { createPatch } from 'diff';

const patch = createPatch(
  'file.txt',
  'original text',
  'modified text',
  'Original',
  'Modified'
);

applyPatch(oldStr, patch)

Apply a patch to a string.

import { applyPatch } from 'diff';

const result = applyPatch('original text', patch);

Options

OptionTypeDefaultDescription
ignoreCasebooleanfalseIgnore case differences
ignoreWhitespacebooleanfalseIgnore whitespace
newlineIsTokenbooleanfalseTreat newlines as separate tokens

Return Value

All diff functions return an array of change objects:

[
  { value: 'common text', added: undefined, removed: undefined },
  { value: 'added text', added: true, removed: undefined },
  { value: 'removed text', added: undefined, removed: true }
]