Unified Diff Parser

0.12.0 · active · verified Tue Apr 21

parse-diff is a lightweight and focused JavaScript library designed to parse unified diff format strings, typically generated by version control systems like Git. It transforms a raw diff string into a structured JavaScript array of file objects, each containing chunks of changes and individual line modifications, including metadata like additions, deletions, and file paths. The current stable version is 0.12.0, published in January 2023, indicating a mature and stable project with an infrequent release cadence. While other parsers exist (e.g., `diffparser`, `parse-git-diff`), `parse-diff` is known for its simplicity and direct approach to the unified diff format, making it suitable for applications requiring programmatic access to diff data. It ships with TypeScript types, enhancing developer experience for TypeScript projects.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to parse a simple unified diff string and iterate through the resulting file, chunk, and change objects, logging their properties.

import parse from 'parse-diff';

const diffString = `diff --git a/README.md b/README.md
index c96dc36..0e564d2 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,6 @@
 # parse-diff
 
 Simple unified diff parser for JavaScript
 
-## JavaScript Usage Example
+## Usage Example
+
 `;

const files = parse(diffString);

console.log(`Number of patched files: ${files.length}`);

files.forEach(file => {
  console.log(`\nFile: ${file.from} -> ${file.to}`);
  console.log(`  Additions: ${file.additions}, Deletions: ${file.deletions}`);
  file.chunks.forEach(chunk => {
    console.log(`  Chunk content: ${chunk.content}`);
    chunk.changes.forEach(change => {
      console.log(`    Line (${change.type}): ${change.content}`);
    });
  });
});

view raw JSON →