Examples
Example 1: Compare Two Text Files
import { diffLines } from 'diff';
const oldText = `Line 1
Line 2
Line 3`;
const newText = `Line 1
Line 2 modified
Line 3`;
const diff = diffLines(oldText, newText);
diff.forEach((part) => {
const color = part.added ? '\x1b[32m' :
part.removed ? '\x1b[31m' : '\x1b[0m';
process.stdout.write(color + part.value + '\x1b[0m');
});
Example 2: Compare Configuration Files
import { diffJson } from 'diff';
const oldConfig = {
server: 'localhost',
port: 3000,
debug: false
};
const newConfig = {
server: 'localhost',
port: 8080,
debug: true,
ssl: true
};
const diff = diffJson(oldConfig, newConfig);
// Output the differences
console.log('Configuration changes:');
diff.forEach((part) => {
if (part.added) {
console.log('+', part.value);
} else if (part.removed) {
console.log('-', part.value);
}
});
Example 3: Generate HTML Diff
import { diffWords } from 'diff';
function generateHtmlDiff(oldText, newText) {
const diff = diffWords(oldText, newText);
return diff.map((part) => {
if (part.added) {
return `<ins>${part.value}</ins>`;
}
if (part.removed) {
return `<del>${part.value}</del>`;
}
return part.value;
}).join('');
}
const html = generateHtmlDiff(
'The quick brown fox',
'The fast brown fox'
);
// Output: The <del>quick</del><ins>fast</ins> brown fox
Example 4: Create and Apply Patches
import { createPatch, applyPatch } from 'diff';
const oldText = 'Hello World';
const newText = 'Hello Universe';
// Create a patch
const patch = createPatch(
'greeting.txt',
oldText,
newText,
'Original',
'Modified'
);
console.log(patch);
// Output:
// --- Original
// +++ Modified
// @@ -1 +1 @@
// -Hello World
// +Hello Universe
// Apply the patch
const result = applyPatch(oldText, patch);
console.log(result); // 'Hello Universe'