diff
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
The diff package, otherwise known as jsdiff, is a JavaScript implementation for text differencing. It is based on the algorithm proposed in "An O(ND) Difference Algorithm and its Variations". It is used to compare two blocks of text and highlights the differences between them. This comparison can be made character by character, word by word, line by line, and even sentence by sentence. It can also compare CSS tokens, JSON objects, and arrays. Additionally, it provides functionality for creating a unified diff patch, applying a patch, and parsing a patch into structured data.
To use the diff package, you first need to install it via npm using the command npm install diff --save
. Once it is installed, you can require it in your JavaScript file and start using its methods. Here are a few examples:
const Diff = require('diff');
const one = 'good morning';
const other = 'good afternoon';
const diff = Diff.diffWords(one, other);
diff.forEach((part) => {
if(part.added) {
console.log('Added: ' + part.value);
} else if(part.removed) {
console.log('Removed: ' + part.value);
} else {
console.log('Common: ' + part.value);
}
});
This code will output the words added, removed, and in common between the two strings.
Here's another example which illustrates how to compare two JSON objects:
const Diff = require('diff');
const oldObj = {name: "John", age: 30, city: "New York"};
const newObj = {name: "John", age: 31, city: "London"};
const diff = Diff.diffJson(oldObj, newObj);
diff.forEach((part) => {
if(part.added) {
console.log('Added: ' + JSON.stringify(part.value));
} else if(part.removed) {
console.log('Removed: ' + JSON.stringify(part.value));
}
});
This code will output the fields added and removed from the old JSON object to the new JSON object.
The documentation for the diff package can be found in the README file present in its GitHub repository. It details how to install the package, lists all its API methods, explains what each method does, and provides examples of how to use them.