Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท util, assert and the Test Runner

Node.js util.diff() function

Reference for util.diff() in Node.js: compute the edit script between two strings or arrays as [operation, value] pairs, and turn it into a readable diff.

util.diff(actual, expected) compares two strings or two arrays and returns the list of steps that turns one into the other. Every step is a pair [operation, value]: 0 for a part both sides share, 1 for a part only in actual, and -1 for a part only in expected.

It is the same kind of algorithm that sits behind the diff shown by assert when two values differ. Strings are compared character by character, and arrays element by element. It is a fairly new function, so check that your Node version has it, and treat its exact output format as something to verify when you upgrade.

NODE
import { diff } from "node:util";

console.log(diff("abc", "abd"));
// [ [ 0, 'a' ], [ 0, 'b' ], [ 1, 'c' ], [ -1, 'd' ] ]

Try it

Node.js Diffing strings and arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Printing a readable diff

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
util.diff(actual: string | string[], expected: string | string[]): Array<[-1 | 0 | 1, string]>
Name Description
actual The value you have. A string or an array of strings.
expected The value you wanted. Same kind as actual.

Returns: an array of [operation, value] pairs in order. value is one character for strings and one element for arrays.

Errors: other argument types, or array elements that are not strings, throw ERR_INVALID_ARG_TYPE.

Usage notes

  • 1 marks content that is in actual but not in expected, -1 the opposite (the runner printed [ 1, "c" ] for diff("abc", "abd")).
  • Equal inputs give an array in which every step has operation 0, and two empty inputs give [].
  • The result is a minimal edit script, so repeated or moved items may come out as a delete plus an insert instead of a "move".
  • Arrays must contain only strings; a number or object element throws ERR_INVALID_ARG_TYPE. Serialize other data (for example with JSON.stringify per item) before diffing.
  • Diffing very long inputs is expensive, because the work grows with the number of differences and the input size.
  • For plain "are they equal?" questions use util.isDeepStrictEqual() instead; for test failures, assert already prints a diff for you.